1

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?

Community
  • 1
  • 1
Dan Denney
  • 290
  • 2
  • 14

3 Answers3

4

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.

fairidox
  • 3,358
  • 2
  • 28
  • 29
  • I'm marking this one as the answer because you led me to playing with parseFloat and toFixed. I can run the number out as long as I want it seems. Thank you! – Dan Denney Nov 22 '11 at 19:37
2

This is because of floating point math

Jan Dragsbaek
  • 8,078
  • 2
  • 26
  • 46
1

The number type javascript uses is the IEEE 754-2008 floating point type and has known acurracy issues...

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158