Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of 3 variables: strange behavior [duplicate]

Possible Duplicate:
Is JavaScript's Math broken?
Why can't decimal numbers be represented exactly in binary?

What will be result of next code:

if(0.3 == ( 0.1 + 0.1 + 0.1 ))
{
      alert(true);
}
else
{
      alert(false);
}

It is strange, but result will be false.

Reason is that result of

0.1+0.1+0.1

will be

0.30000000000000004

How can be explained this behavior?

like image 254
Anton Avatar asked Sep 30 '11 09:09

Anton


2 Answers

It's the same reason 1/3 + 1/3 + 1/3 may not give you exactly 1 in decimal. If you use 1/3 as .33333333, then 1/3 + 1/3 + 1/3 will give you .9999999 which isn't exactly one.

Unless you know exactly what you're doing, don't compare non-integer numeric types for equality.

like image 70
David Schwartz Avatar answered Sep 21 '22 07:09

David Schwartz


The explanation is pretty simple - read about Floating Point Numbers Problems

like image 44
Tudor Constantin Avatar answered Sep 18 '22 07:09

Tudor Constantin