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.
Percentage can be calculated by dividing the value by the total value, and then multiplying the result by 100. The formula used to calculate percentage is: (value/total value)×100%.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With