Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell printf to string

Tags:

string

haskell

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
like image 481
Zhen Avatar asked Mar 22 '13 08:03

Zhen


2 Answers

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
like image 176
Chris Taylor Avatar answered Nov 15 '22 07:11

Chris Taylor


Text.Printf might be what you need.

like image 28
swpd Avatar answered Nov 15 '22 07:11

swpd