Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating percentages in js [duplicate]

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.

like image 757
James Avatar asked May 10 '13 19:05

James


People also ask

How do you extract percentages?

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%.


1 Answers

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);
like image 169
Denys Séguret Avatar answered Oct 02 '22 17:10

Denys Séguret