Formatting output
Text.Printf
Text.Printf is in the boot libraries and it is the shortest way from values to a formatted line. The format string is a String and the type of the result depends on how it is used:
printf :: PrintfType r => String -> r
printf "%d items at %s each\n" (3 :: Int) "2.50"
In a do block as a statement the result is IO () and the line is printed; in a putStrLn or a show position it is a String. The same function does both, and the format controls the spaces, the decimals and the alignment.
module Main (main) where
import Text.Printf (printf)
main :: IO ()
main = do
printf "%d items at %s each\n" (3 :: Int) "2.50"
printf "%.2f and %8.3f\n" (3.14159 :: Double) (2.5 :: Double)
printf "%-8s|%8s|\n" "left" "right"
printf "%04d\n" (42 :: Int)
printf "%x %o\n" (255 :: Int) (8 :: Int)
ghc -Wall -O1 -o formats formats.hs
./formats
3 items at 2.50 each
3.14 and 2.500
left | right|
0042
ff 10
%.2f rounds to two decimals, %8.3f pads the field to eight characters, a negative width aligns to the left and %04d fills with zeros. The last line shows the base conversions: 255 in hexadecimal is ff and 8 in octal is 10, both without a prefix.
Widths, precision and alignment
- %5d right-aligns an integer in five characters; %-5d left-aligns it.
- %8.2f is eight characters wide with two decimals, and a number that needs more room widens the field instead of being cut.
- %s takes a String; a Text has to be unpacked first, and a Show value has to be shown.
- %d needs an integral type and %f a real one, and a mismatch is a type error at compile time, which is the good news about a typed printf.
A fixed-width table
The real use is a report. A row is a record, a line is one printf, and the header uses the same widths so the columns line up:
module Main (main) where
import Text.Printf (printf)
data Row = Row
{ rowName :: String
, rowCount :: Int
, rowPrice :: Double
}
rows :: [Row]
rows =
[ Row "tea" 3 2.5
, Row "coffee beans" 12 9.75
, Row "cake" 1 4.0
]
line :: Row -> String
line row =
printf "%-14s %4d %8.2f" (rowName row) (rowCount row) (rowPrice row)
main :: IO ()
main = do
putStrLn (printf "%-14s %4s %8s" "item" "qty" "price")
mapM_ (putStrLn . line) rows
printf "%-14s %4d %8.2f\n" "total" (sum (map rowCount rows)) (sum (map (\r -> rowPrice r * fromIntegral (rowCount r)) rows))
ghc -Wall -O1 -o table table.hs
./table
item qty price
tea 3 2.50
coffee beans 12 9.75
cake 1 4.00
total 16 128.50
The total is computed from the rows and formatted with the same widths, so it sits under the column it belongs to. Each line is a pure Row -> String, which means the table can be tested without IO and the printing is one mapM_ at the end. That split is the same one the report monoid of the earlier lesson used.
Numeric and showFFloat
When the number is the value and not a label, Numeric gives the string and the caller decides what to do with it:
module Main (main) where
import Numeric (showFFloat, showHex)
main :: IO ()
main = do
print (showFFloat (Just 2) (3.14159 :: Double) "")
print (showFFloat Nothing (2.5 :: Double) "")
print (showHex (255 :: Int) "")
print (showFFloat (Just 0) (2.5 :: Double) "")
ghc -Wall -O1 -o numeric numeric.hs
./numeric
"3.14"
"2.5"
"ff"
"2"
showFFloat takes the number of decimals as a Maybe Int, where Nothing means as few as the value needs, and a suffix that is appended to the result. Just 0 rounds 2.5 to 2, which is the banker-friendly rounding of the underlying show and worth knowing before a financial report. These functions return a String with no newline, so they compose with the table of the previous section.
Exercises
- Print a price list with the name, the quantity and the price in three aligned columns.
- Format the same number with %f, %e and %g and compare.
- Write a row function that takes the width of the name column as an argument.
- Print a percentage with one decimal and a percent sign.
- Use showFFloat (Just 2) to format a total and append a currency code.
- Explain what happens when the name is wider than its column and why the table still lines up.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
printf "%.2f"control?Answer
Two digits after the decimal point
The dot introduces the precision, which for a float is the number of decimals.
-
What does
%-8sdo with a string?Answer
Pads it to eight characters, aligned left
The minus sign flips the alignment to the left, as the left and right line showed.
-
What does
printfreturn in adoblock statement position?Answer
IO ()PrintfType resolves to IO () in a statement and to String where a string is needed.
-
What does this program print?
module Main (main) where import Text.Printf (printf) main :: IO () main = printf "%04d" (42 :: Int)Answer
0042
The zero flag fills the width of four with zeros.
-
Which value does
showFFloat (Just 0) 2.5 ""give?Answer
"2"
The round-to-even of the underlying show gives 2 for 2.5 at zero decimals.
-
What does this program print?
module Main (main) where import Text.Printf (printf) main :: IO () main = printf "%x" (255 :: Int)Answer
ff
The x conversion prints the hexadecimal digits in lower case and without a prefix.
-
Why is a width that is too small not a truncation?
Answer
The field widens to fit the value, so nothing is lost
A printf width is a minimum, so a longer value widens the column.
-
Which format string left-aligns a string in a field of eight characters?
Answer
%-8sThe minus sign asks for left alignment and 8 is the minimum width.
-
What does
showHexreturn?Answer
A
Stringof the hexadecimal digitsNumeric functions format into a String, which the caller can print or combine.
-
Why is a printf format a type-checked thing in Haskell?
Answer
The type of the arguments and the result is checked at compile time
PrintfType and the typed format make a mismatch such as %d with a String a compile error.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev