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
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
Text.Printf might be what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With