Float format?

676 views
Skip to first unread message

Carl Olsen

unread,
Dec 2, 2013, 10:16:08 AM12/2/13
to elm-d...@googlegroups.com
Hi,

For some reason I can't find any good solutions for formating for example floats.
If I have for example 1.23456 and i want it to be formatted to two decimals 1.23?? 

Right now I made my own function, where i multiply by 100 and round it and then divide by 100, but it seems that there should be a better/more efficient way of doing this??
I know this function isn't totally correct, but for my case that is not an issue.

    testFun fl = let first = fl*100
                         sec = round first
                         third = toFloat sec / 100.0
                     in third

    main = asText (testFun 1.2345678)


Cheers 

Dobes Vandermeer

unread,
Dec 2, 2013, 1:03:49 PM12/2/13
to elm-d...@googlegroups.com
I suggest you avoid the built-in formatting altogether, since you never know when your division by 100 will still produce a really long number anyway because of floating-point rounding.

To be certain you get the right result, I would suggest that you multiply by 100, round to an integer, convert to a string, and then insert the decimal point yourself 2 away from the end.  You can optionally trim zeroes from the end, too, if you don't want a strict 2 decimal places.




--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Mikael Bohman

unread,
Dec 3, 2013, 8:03:41 AM12/3/13
to elm-d...@googlegroups.com
How do you convert the int to a string ??

Carl Olsen

unread,
Dec 3, 2013, 8:30:45 AM12/3/13
to elm-d...@googlegroups.com
"show" works, but its hard to find documentation on this..

e.g
main = asText <| show 1

Jeff Smits

unread,
Dec 3, 2013, 8:34:24 AM12/3/13
to elm-discuss
Interesting.. I thought it would be in either the Basisc library docs or the String library docs but I can't find it there...

Max Goldstein

unread,
Dec 3, 2013, 2:25:00 PM12/3/13
to elm-d...@googlegroups.com
These functions are in Prelude and not Basics for some reason. I don't recall Evan publicizing the change in name, and while I agree with it, I wish he'd complete the move or give a reason why we're stuck in this limbo. Not that he's working on any big important projects at the moment or anything.
Reply all
Reply to author
Forward
0 new messages