Calculating percentages in js

13,455

Solution 1

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);

Solution 2

Not all decimal numbers have exact representations in binary, so problems like this happen pretty regularly when you try to do math with floats.

Converted to binary, your operation is as follows:

106 = 64 + 32 + 8 + 2 = 1101010
100 = 64 + 32 + 4 = 1100100
1101010 / 1100100 = 1010.10011001100...

You then multiply this by 10, or 101 in binary and get

1010.10011001100... * 101 = 1010.1001100110011001100...

Which does not quite evaluate to 10.6.

In your particular case, the number has been truncated at 1010.10011001100110011001100110011001, or 36 bits.

Solution 3

Try Below :

Var myAnswer = 106 / 100 * 10;
var result = myAnswer.toFixed(1);

Javascript: formatting a rounded number to N decimals

How this will work for you...

Enajoy your day..!!!

Share:
13,455
James
Author by

James

Updated on June 13, 2022

Comments

  • James
    James almost 2 years

    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.

  • Denys Séguret
    Denys Séguret about 11 years
    It's true that changing the order of operation can lead to different approximation and, here, to a different result, but the fundamental principles is that we can't generally aim for results that are displayabe without formatting.