Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round number to specified number of digits

Tags:

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.

like image 757
amindfv Avatar asked Sep 16 '12 20:09

amindfv


People also ask

How many digits does excel round to?

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.

How do you round a number into 2 digits?

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.


2 Answers

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

 (fromInteger $ round $ f * (10^n)) / (10.0^^n) 
like image 190
aland Avatar answered Sep 23 '22 22:09

aland


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).

like image 24
nponeccop Avatar answered Sep 22 '22 22:09

nponeccop