Comparing Numbers for Exact Equality in JavaScript

Overall I like JavaScript a lot but the language does have some quirks. One of these quirks involves a potentially nasty error when you write code to compare two numeric values for exact equality. Consider this example:

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

Here the i != 1.0 condition might never be true and you’d have an infinite loop. The moral is: when comparing two numbers with decimal points in JavaScript for exact equality be careful.

This entry was posted in Software Test Automation. Bookmark the permalink.