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.
As a result, the amount of precision possible may vary depending on the size of the number (the mantissa) being manipulated. In the case of Excel, although Excel can store numbers from 1.79769313486232E308 to 2.2250738585072E-308, it can only do so within 15 digits of precision.
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
Not sure whether any standard function exists, but you can do it this way:
(fromInteger $ round $ f * (10^n)) / (10.0^^n)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With