[Haskell-beginners] How to convert a float or double number into a string?

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Sep 18 15:00:59 CEST 2013


On 18 September 2013 13:48, yi lu <zhiwudazhanjiangshi at gmail.com> wrote:
> If I use `show`,
> show 123.45, it will return "123.45", a desired answer.
>
> However, for
> show 123.45678901234567890, it will return
> "123.45678901234568".
>
> I want to save all digits into a string. I suppose I use a wrong type of
> number, which is Float.

Yes, it is the wrong type of number. Float can only store finitely
many digits and you're asking for slightly too many. Also even if it
*looks like* float has enough digits for your number in fact it has
converted them from decimal to binary. For non-integers exact decimal
to binary conversion is rarely possible. In this case the nearest
binary float is 123.4567890123456805895330035127699375152587890625 but
many of these decimal digits will be truncated from display.

> But what can I do to work right?

Are rational numbers acceptable in your problem?
http://stackoverflow.com/questions/7056791/how-to-parse-a-decimal-fraction-into-rational-in-haskell


Oscar



More information about the Beginners mailing list