[Haskell-cafe] Proper rounding of floating-point values

Troels Henriksen athas at sigkill.dk
Tue Jul 17 13:00:25 UTC 2018

Much to my surprise, there does not seem to be a function in base (let
alone the Prelude) that rounds floating point numbers correctly in the
presence of NaNs and infinities.  For example:

  > round (0/0 :: Double) :: Int
  > round (0/0 :: Double) :: Integer
  > round (1/0 :: Double) :: Int
  > round (1/0 :: Double) :: Integer

This is because the 'round' function must return an instance of
Integral, which Double is not.  In the presence of NaNs and infinities,
this does not fly.  In my own code, I ended up just using the FFI to
call out to C, which is simple enough:

  foreign import ccall "round" c_round :: Double -> Double
  foreign import ccall "roundf" c_roundf :: Float -> Float

However, it does disturb me a bit that I cannot find a standard way to
do this fairly common operation.

(GHC's implementation does seem to avoid many other common pitfalls[0],
probably because it does use C's round() under the covers.)

[0]: https://www.cockroachlabs.com/blog/rounding-implementations-in-go/

\  Troels
/\ Henriksen

More information about the Haskell-Cafe mailing list