Erlang Central

Difference between revisions of "Floating Point Rounding"

From ErlangCentral Wiki

 
Line 61: Line 61:
  
  
[[Category:CookBook]]
+
[[Category:CookBook]][[Category:NumberRecipes]]

Revision as of 23:01, 3 September 2006

Problem

You need to round a floating-point number to an integer.

Solution

Use one of the procedures erlang:round, ceiling, floor and erlang:trunc. Note, the standard Erlang distribution does not come with either floor or ceiling, but they can be easily implemented in terms of erlang:trunc:

floor(X) ->
    T = erlang:trunc(X),
    case (X - T) of
        Neg when Neg < 0 -> T - 1;
        Pos when Pos > 0 -> T;
        _ -> T
    end.

ceiling(X) ->
    T = erlang:trunc(X),
    case (X - T) of
        Neg when Neg < 0 -> T;
        Pos when Pos > 0 -> T + 1;
        _ -> T
    end.

1> floor(-4.3).
-5
2> ceiling(-4.3).
-4
3> erlang:trunc(-4.3).
-4
4> erlang:round(-4.3).
-4
5> floor(3.5).
3
6> ceiling(3.5).
4
7> erlang:trunc(3.5).
3
8> erlang:round(3.5).
4
9> erlang:round(7).
7

The procedures all return integers.

erlang:round returns the closest integer to x, rounding to even when x is halfway between two integers. floor returns the largest integer not larger than x. ceiling returns the smallest integer not smaller than x. erlang:trunc returns the integer closest to x whose absolute value is not larger than the absolute value of x.

If the number given to one of the procedures is inexact?, then the result will also be inexact.

See Also

Further general information on math and rounding is available from:

MathWorld definition of the Floor Function. MathWorld definition of the Ceiling Function