Using trunc function in Erlang

Sean Hinde <>
Sat Dec 31 01:28:59 CET 2005


On 30 Dec 2005, at 19:50, Erlang Questions wrote:

> I was afraid about that.
> Unfortunately, these numbers represent money in my application :o(

I would hope that the folks setting the requirements for your system  
(customers? potential customers?) will have a pretty clear idea how  
many decimal places you should be working to and how to do rounding  
of money.

Certainly anything I have worked on in the telecom space caring for  
money (including billing mediators and pre-paid systems) has had  
pretty clear requirements in this area.

Sean

>
> Regards, Carlos.-
>
> ----- Original Message -----
> From: "Richard Cameron" <>
> To: "Erlang Questions" <>
> Cc: "Erlang Questions" <>
> Sent: Friday, December 30, 2005 3:35 PM
> Subject: Re: Using trunc function in Erlang
>
>
>>
>> On 30 Dec 2005, at 18:15, Erlang Questions wrote:
>>
>>> Hello everybody, I have one question about Erlang trunc function.
>>>
>>> Why Erlang behaves like this?
>>>
>>> 1> trunc(1.3/0.1).
>>> 13
>>> 2> trunc(1.4/0.1).
>>> 13
>>> 3> trunc(1.5/0.1).
>>> 15
>>
>> Unfortunately, this isn't an Erlang problem at all. Look at the
>> output of this little C program on my machine:
>>
>> wilt:/tmp rcameron$ cat floor.c
>> #include <math.h>
>> #include <stdio.h>
>> main() {
>>          printf("%f\n", floor(1.4/0.1));
>> }
>> wilt:/tmp rcameron$ gcc -o floor floor.c
>> wilt:/tmp rcameron$ ./floor
>> 13.000000
>>
>> Computers have a nasty habit of doing things you might not
>> intuitively expect with floating point operations. You sort of just
>> have to accept that float operations are not exact, so the  
>> computation:
>>
>> 1.4/0.1
>>
>> actually produces a result in the range
>>
>> 14.0000000000000 +/- epsilon
>>
>> where epsilon is (very) small. Unfortunately, in your case, it's
>> every so slightly negative, so
>>
>> erlang:trunc(14.0000000000000 - Epsilon).
>>
>> evaluates to 13.
>>
>>> And which you think is the best way to manage this in order to
>>> solve this kind of problems?
>>
>> It depends very much what you're trying to do. What do these numbers
>> represent in your application?
>>
>> Richard.
>>
>>
>




More information about the erlang-questions mailing list