Error Correction in JavaScript Maths
Here are two reasons why you need to be careful when doing browser-based mathematical comparison operations in JavaScript:
You can try it for yourself. Open Chrome, press F12 (opens Developer Tools) and navigate to the Console tab. Type in the above equations and see the results for yourself.
It looks broken. But apparently, it's working as expected.
If you happen to be doing some JavaScript validation and working with numbers, this small discrepancy can be a real PITA.
Image you have a bit of code like this:
if ( (x + y) > 0.3 ){ alert("You've exceeded the limit of 0.3"); }
Now, imagine x and y come from user input and they inputted 0.2 and 0.1. They'll be wondering a big WTF.
Instead you need to introduce the concept of Epsilon. Like so:
if ( (x + y) - 0.3 > Epsilon ){ alert("You've reached the limit"); }
Where Epsilon is a very, very small number. How small? Typically something like 0.00000000001.
You've been warned.
I think it's worth pointing out took those new(ish) to JavaScript that these are issues which occur with floating point arithmetic.
If the math on your web page is dealing with currency, then one solution is to convert to integers first (ie. cents/pence), do the math then convert back to dollars/euros/pounds
Reply
Don't forget server side code based on Javascript or Java (for example XPages SSJS have the same issue. And the Java related stuff too like normal Agents.
Reply
“Floating point numbers are like piles of sand; every time you move them around, you lose a little sand and pick up a little dirt.” — Brian Kernighan and P. J. Plauger.
Reply
I don't know a lot about javascript, but wouldn't it be safer to test :
abs( (x + y) - 0.3) > Epsilon
Reply
There are a few libraries out there that can help, if you find you're doing a project that requires a lot of calculations. They tend to be clunky, but useful.
Reply
My advice: get familiar with the Math object in JavaScript and use it often.
http://www.w3schools.com/js/js_obj_math.asp
Reply
see especially: http://www.w3schools.com/jsref/jsref_obj_math.asp
(detailed reference for Math object)
Reply