Haskell:
Rounding numbers

How to:

Haskell uses the round, ceiling, floor, and truncate functions from the Prelude for rounding operations.

import Prelude

main :: IO ()
main = do
  let num = 3.567
  print $ round num    -- 4
  print $ ceiling num  -- 4
  print $ floor num    -- 3
  print $ truncate num -- 3
  
  -- Rounding to a specific decimal place is not in Prelude.
  -- Here's a custom function:
  let roundTo n f = (fromInteger $ round $ f * (10^n)) / (10.0^^n)
  print $ roundTo 1 num -- 3.6

Deep Dive

Historically, rounding is significant in numerical analysis and computer science because it’s crucial to minimizing error accumulation in computations, particularly before floating-point representations were standardized with IEEE 754.

What to round to? round takes you to the nearest integer—up or down. ceiling and floor always round up or down to the closest integer, respectively, while truncate simply drops the decimal points.

Alternatives to these functions might involve custom logic, like our roundTo, or you might pull in libraries (like Data.Fixed) for more complex requirements.

Watch out for unexpected results due to how Haskell handles half-way cases in round (it rounds to the nearest even number).

See Also