e r l a n g : c o o k b o o k

/ Erlang.NumberRounding

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Rounding Floating-Point Numbers

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

Discussion

The procedures all return integers.

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:

Contributors

Based on work by ChandraQuintas and JensAxelSoegaard.

-- BrentAFulgham - 23 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 030

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest