Floating point numbers in JavaScript
// January 25th, 2011 // 1 Comment » // labs
A few weeks ago, I was doing a freelance for my friends of Gruponat when I got with this JavaScript problem. I was doing the following arithmetical function: “0.9 + 0.1″. To my surprise, the result wasn’t “1″ as I spected.
Numbers are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits. Integers up to just over 9e15 are precise, but few decimal fractions are. Because they are floating point numbers, they do not always exactly represent real numbers, including fractions. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.
The problem is that although you can input and they are show as common floating points numbers, internally they aren’t. This mean that a JavaScript program can not represent exactly some numbers like 0.3 or 0.1 (0.1; 0.001; etc) but it can represent others like 0.20 or 0.5. What you could do is something like this:
var floatnumber1 = 0.9; var floatnumber2 = 0.1; var result = Math.round(((floatnumber1*100) + (floatnumber2*100))/100));
And what about if we make more complex? In my case in need to represent the number in the HTML with a comma instead of a dot, like this ’0,9′. So when I take the number from the HTML with JavaSript I have to convert from string to a floating point numbers. What I have to do first is convert the string with the JavaScript Global Functions ‘replace’:
var floatnumber1 = '0,9';
floatnumber1 = floatnumber1.replace(",",".");
And them I have to transform the string to a floating point numbers with the ‘parseFloat’ JavaScript Global Functions.
floatnumber1 = parseFloat(floatnumber1)
And now, I have my number ready to do the arithmetical function.
var result = Math.round(((floatnumber1*100) + (floatnumber2*100))/100));
Its seems complicated, but its easier with the help of the JavaScript Global Functions. To finish, here is the final snippet, optimized just in one line. I add some code to the transform the floating point number to string again, adding the “” at the end, and them I replace the dot with the comma, to show it as the client want.
var floatnumber1 = '0,9';
var floatnumber2 = '0,1';
document.write(((Math.round((parseFloat(floatnumber1.replace(",","."))*100) + (floatnumber2.replace(",","."))/100) + "").replace(".",","));
In my next post I will be talking a little bit more about the JavaScript Global Functions, because I think be use to ignore them, using frameworks or just because we just don’t take the time to investigate if already exist a way to do some things, and they are a very powerful tool.

[...] my last post, where I wrote about the Javascript problems with the float point numbers, I told that I would be [...]