Reputation: 4283
Is there a sprintf equivalent in Haskell?
I need to convert and format double values into strings.
Is there another way without using printf kind of functions?
The main problem is to avoid:
Prelude> putStrLn myDoubleVal
1.7944444444444447e-2
Instead, I want this:
Prelude> putStrLn . sprintf "%.2f" $ myDoubleVal
1.79
Upvotes: 22
Views: 9787
Reputation: 326
Formatting is an option to create formatted string, if you want '"s"printf' and don't need full compatibility with printf style.
Upvotes: 0
Reputation: 47382
Yes, it's in the Text.Printf module, and it's just called printf
.
> import Text.Printf
> let x = 1.14907259
> putStrLn . printf "%.2f" $ x
1.15
Note that the return type of printf
is overloaded, so that it's capable of returning a String
(as in the example above) but it's also capable of returning an I/O action that does the printing, so you don't actually need the call to putStrLn
:
> printf "%.2f\n" x
1.15
Upvotes: 55