Possible Duplicate:
Is JavaScript's Math broken?
Suppose,
var x = .6 - .5;
var y = 10.2 – 10.1;
var z = .2 - .1;
Comparison result
x == y; // false
x == .1; // false
y == .1; // false
but
z == .1; // true
Why Javascript show such behavior?
Because floating point is not perfectly precise. You can end up with slight differences.
(Side note: I think you meant
var x = .6 - .5;Otherwise, you’re comparing-0.1with0.1.)JavaScript uses IEEE-754 double-precision 64-bit floating point (ref). This is an extremely good approximation of floating point numbers, but there is no perfect way to represent all floating point numbers in binary.
Some discrepancies are easier to see than others. For instance:
There are some JavaScript libraries out there that do the “decimal” thing a’la C#’s
decimaltype or Java’sBigDecimal. That’s where the number is actually stored as a series of decimal digits. But they’re not a panacea, they just have a different class of problems (try to represent1 / 3accurately with it, for instance). “Decimal” types/libraries are fantastic for financial applications, because we’re used to dealing with the style of rounding required in financial stuff, but there is the cost that they tend to be slower than IEEE floating point.Let’s output your
xandyvalues:No great surprise that
0.09999999999999998is!=to0.09999999999999964. 🙂You can rationalize those a bit to make the comparison work:
Or a more generalized solution:
Live example | source
Note that it’s still possible for accuracy crud to be in the resulting number, but at least two numbers that are very, very, very close to each other, if run through
roundwith the same number of places, should end up being the same number (even if that number isn’t perfectly accurate).