Erlang Central

# Difference between revisions of "Floating Point Rounding"

From ErlangCentral Wiki

## 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.