var x = 1.0 / 3.0;
var y = 0.33333333;
if (x == y)
alert(‘Using naive direct compare x and y are equal’);
alert(‘Using naive direct compare x and y are NOT equal’);
This code will generate the not-equal message on most systems. The usual way to deal with this is to use the built-in toFixed and parseFloat functions like so:
if (parseFloat(x.toFixed(8)) == parseFloat(y.toFixed(8)))
alert(‘Using toFixed and parseFloat x and y are equal’);
alert(‘Using toFixed and parseFloat x and y are not equal’);
This code generates the are-equal message.
The toFixed function operates on a numeric value and returns a string with the specified number of decimals. The parseFloat function accepts the resulting string and returns a numeric. Note that we really don’t need the parseFloat function because then we’d be comparing two strings which would work:
if (x.toFixed(8) == y.toFixed(8)) . . .
Now the example I’ve presented here is pretty obvious. The nasty situations are ones which aren’t so crude. Consider this:
var inc = 0.33;
for (var i = 0.0; i != 1.0; i += inc)
// do something