Erlang Central

Difference between revisions of "Floating Point Rounding"

From ErlangCentral Wiki

m (Reverted edits by Kaiserpanda (Talk); changed back to last version by Ayrnieu)
Line 56: Line 56:
[ blackjack hints]
[ online casino for cash]
[ casino games online]
[ free online casino tournament]
[ free online casino tournament]
[ internet casinos sites]
[ play casino games games online]
[ online casino tips]
[ casinos portal]
[ casinos games]

Revision as of 08:50, 4 December 2006


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


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

floor(X) ->
    T = trunc(X),
    case X - T < 0 of
        true -> T - 1;
        false -> T

ceiling(X) ->
    T = trunc(X),
    case X - T < 0 of
        true -> T;
        false -> T + 1

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

The procedures all return integers.

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

Further general information on math and rounding is available from:

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