4 Replies Latest reply on Mar 26, 2014 2:47 PM by GordonSmith

Sum with negative Number

Hi All,

I have problem when sum negative number.

Here is sample:

var a:Number = 4.2;

var b:Number = 4.4;

var c:Number = -8.6;

var total:Number = a+b+c;

The value of total = 1.7763568394002505E-15. So strange, the value of total should is 0.

Anybody can help me explain this problem in actionscript and how to fix it ?

Thanks,

ndt

• 1. Re: Sum with negative Number

See past threads on how floating point numbers work.  Use toPrecision or toFixed to convert the Number to String

• 2. Re: Sum with negative Number

hi Flex harUI,

I can fix this problem but I want to know why the result is 1.7763568394002505E-15. can you explain for me ?

Thanks,

ndt

• 3. Re: Sum with negative Number

http://floating-point-gui.de/basic/

1.7763568394002505E-15.

is really

0.00000000000000017763568394002505

So it's a tiny number, almost zero but not quite.

Binary nubers aren't always able to represent floating point values precisely.

It's not actionscript specific - it applies to computers in general.

• 4. Re: Sum with negative Number

Floating point numbers are stored in binary. The fractional bits represent 1/2, 1/4, 1/8, etc. not, 1/10, 1/100, 1/1000. A decimal number like 4.2 cannot be stored exactly in binary, because in binary 0.2 has an infinite repeating sequence of binary fractional digits. Think about trying to represent 1/5 when all you've got to work with is 1/2, 1/4, 1/8, etc.