6

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.

James
  • 969
  • 1
  • 8
  • 13

5 Answers5

5

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);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

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.

ckersch
  • 7,507
  • 2
  • 37
  • 44
1

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

Community
  • 1
  • 1
Kishan Patel
  • 1,358
  • 10
  • 24
0

Double precision. Numbers are stored in the computer as powers of two, e.g. 1/2 + 1/4 + 1/8... so when printed as decimals they may not be exact.

Jason
  • 13,563
  • 15
  • 74
  • 125
0

you could try (106 / 1000) * 100

code_cookies
  • 3,910
  • 4
  • 16
  • 14
  • 1
    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. – Denys Séguret May 10 '13 at 19:20