Is there a simple function to round a Double
or Float
to a specified number of digits? I've searched here and on Hoogle (for (Fractional a) => Int -> a -> a
), but haven't found anything.
3 Answers
Not sure whether any standard function exists, but you can do it this way:
(fromInteger $ round $ f * (10^n)) / (10.0^^n)
-
1Looks like noone's jumping in with a standard-library version, so I'm going to mark this as accepted -- works great; thanks.– amindfvSep 17, 2012 at 1:43
It depends on what you are going to do with the rounded number.
If you want to use it in calculations, you should use Data.Decimal
from Decimal
library.
If you want just to format the number nicely, you should use Text.Printf
from the standard library (base
package).
λ: ((/100) $ fromIntegral $ round (0.006 * 100)) == 0.006
λ: False
λ: ((/100) $ fromIntegral $ round (0.06 * 100)) == 0.06
λ: True
(fromInteger $ round $ f * (10^n)) / (10.0^^n)
Integer
.Double
andFloat
are always binary fractions. If someone tells you that you can round them to a specified number of decimal digits, they are lying.