How do I pad string representations of integers in Haskell?
printf
style formatting is availble via the Text.Printf
module:
import Text.Printf
fmt x = printf "%02d" x
Or to special case the formatting of 0:
fmt 0 = " "
fmt x = printf "%02d" x
> (\x -> replicate (3 - length x) '0' ++ x) "2"
"002"
> (\x -> replicate (3 - length x) '0' ++ x) "42"
"042"
> (\x -> replicate (3 - length x) '0' ++ x) "142"
"142"
> (\x -> replicate (3 - length x) '0' ++ x) "5142"
"5142"
The above exploits the fact that replicate
returns the empty string on negative argument.