I am trying to round a number to two digits in Haskell, so if the
output let's say is 1.98887779, I want it to only outpts 1.98
If you round that number to two decimal places, it should end up with 1.99.
The way to round a number x
to a given number of decimal places n
is to:
- multiply x by 10 raised to the power of
n
- round this value
- divided it by 10 raised to the power of
n
Thus:
tenPow :: Integer -> Float
tenPow n = 10.0 ^ n
roundN :: Float -> Integer -> Float
roundN x n = (fromIntegral . round) (x * tenPow n) / tenPow n
The round
function is a little bit odd if you approach it from a non-mathematical point-of-view.
I would expect:
- 3.5 -> 4
- 4.3 -> 4
- 4.5 -> 5
- 4.8 -> 5
But Haskell, for good mathematical reasons, does this:
- 3.5 -> 4
- 4.3 -> 4
- 4.5 -> 4
- 4.8 -> 5
That is so round(3.5 + 4.5)
= round 3.5
+ round 4.5
.
https://typeclasses.com/featured/rounding