by Nigel McFarlane
Sep 5, 2003
Page 5 of 5
Five Drops of Wisdom: How to Stay Out of Trouble
Most Web pages don't need fractional numbers. Avoid them and stick with integers. Make sure your array indexes are whole numbers. Count money in cents, not in dollars. Count percentages in whole percents, not in fractions. Minimize use of division (/) and modulo (%) operations, as they lead straight to floating point in most cases. If you must divide, use the Math.round method afterwards to get your integers back.
If you can perform all the mathematics in your script as integer operations, your numbers will never contain any error. If both operands of the +, - and * operators are integers, and no extreme values occur, then your numbers will remain integers. This is the normal, everyday case. If you must rely on floating point, use guard digitsextra decimal places specified beyond those you actually need. If you require five-digit decimal accuracy, use six, or better yet eight decimal digits. Rounding error creeps into your five important digits far less rapidly when you use three guard digits. Do not rely on always using 17 decimal places. That won't always save you, for example, using 22 digits, all browsers display:
Despite their differences, both examples are correct to 10 significant figures or more.
Do not use numbers too close together or too far apart. Subtracting or comparing two numbers that are very close together is highly error prone. Adding tiny numbers to large numbers is a waste of time, as the tiny number will just disappear to zero. Multiplying small and large numbers together is not a problem. For example, this line of code will not overflow the integer limits, or cause any accuracy problems, even though 12,345,678 is greater than 46,000:
var total = 2 * 12345678; // = 24691356
But the following line of code is likely to be inaccurate because the many significant digits are required to get the difference exactly right:
var total = 0.1 - 0.09; // = 0.010000000000000009
Check your results with isFinite() and isNaN(). If you submit any numerical data via a form, you should always do these checks beforehand, anyway:
var data = document.forms.elements.value;
if (data.isFinite() && ! data.isNaN())
data = parseFloat(data);
Use calculations parsimoniously. The less mathematics you do, the less error will creep in. Treat your floating point numbers gently, keep them safe, and don't work them over and over. You browser (and your users) will love you.