Calculating percentages in js

James picture James · May 10, 2013 · Viewed 13.3k times · Source

I'm trying to create a simple percentage calculator using javascript.

I try a simple calculation in the console (try it):

106 / 100 * 10

And it returns me:

10.600000000000001

What is going on here? Brackets makes no difference and this doesn't occur for every number. I would expect the result to be 10.6 right? Can anyone offer an explanation? This is not browser specific, it happens in Chrome dev tools and firebug.

Answer

Denys Séguret picture Denys Séguret · May 10, 2013

No, the result is correct enough (even if changing the order of operations could lead to a different result), that's one of the miracles of IEEE754 floating point storage : a consequences of the fact that numbers aren't stored like you see them, that is some decimal digits and a comma but as

K * 2 ^ N

where K and N are signed integers.

As of course not all numbers can be stored exactly, others are only approached.

I'd suggest you to read this introduction to IEEE754 computing.

What you need is to format the number when outputting it to the user, for example with

var string = myNumber.toFixed(1);