Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?
I am trying to take numbers and convert them to percentages using jQuery. I’m misunderstanding how javascript performs math functions and I’m wondering if someone could explain why this is happening and/or offer a better way for me to handle it. I’m using the grade school principle of multiplying by 100 to get a percentage.
Here is a fiddle to see it, but I’ll pop my code in here as well. http://jsfiddle.net/dandenney/8wsFd/
$(function() {
var division = 100/600;
var percentage = division * 100;
$("#division").html(division);
$("#percentage").html(percentage);
});
If I run this, division = 0.16666666666666666, but percentage = 16.666666666666664.
Could anyone please tell me why it rounds down and if there is a better way to convert that string into a percentage?
Finite precision. You simply cannot accurately represent repeating numbers with IEEE floating point. You could use or create your own format where you store number as fractions if you care about this level of precision.