Round number to specified number of digits

amindfv picture amindfv · Sep 16, 2012 · Viewed 13.1k times · Source

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.

Answer

aland picture aland · Sep 16, 2012

Not sure whether any standard function exists, but you can do it this way:

 (fromInteger $ round $ f * (10^n)) / (10.0^^n)