-2

I am pretty new in JavaScript and I have found a very strange situation doing an extremely simple mathematical operation: a subtraction.

So in a jQuery function I have this code:

saldoRicalcolato = finanziamento - variazioneAnticipoNumber;

Where finanziamento and variazioneAnticipoNumber are 2 numbers having decimal digits.

It works almost always good except for some specific values.

You can replicate the strange behavior performing this statement into the FireBug console:

2205.88 - 1103.01
1102.8700000000001

So in this case the result is substantially wrong because I obtain 1102.8700000000001 and not 1102.87 as I expected.

Why? What am I missing? Is it a JavaScript engine bug or something like this? Possible?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    Read: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and http://floating-point-gui.de/ In short: that's how the floating point numbers work, not a bug, not a language issue. – Shomz Jan 15 '16 at 12:54
  • 1
    It is not a bug, it's because Js uses floating point numbers, if you know you'll always have 2 decimals, you can use `.toFixed(2)` – Lauromine Jan 15 '16 at 12:56

1 Answers1

6

It's not a JavaScript problem but a more general computer problem. Floating number can't store all decimal numbers properly, because they store stuff in binary For example:

0.5 is store as b0.1 
but 0.1 = 1/10 so it's 1/16 + (1/10-1/16) = 1/16 + 0.0375
0.0375 = 1/32 + (0.0375-1/32) = 1/32 + 00625 ... etc

so in binary 0.1 is 0.00011... but that's endless. Except the computer has to stop at some point. So if in our example we stop at 0.00011 we have 0.09375 instead of 0.1.

It doesn't depend on which language but on the computer, what depends on the language is how you display the numbers. Usually the language will round numbers to an acceptable representation but apparently JavaScript doesn't.

If you're looking to get 1102.87. You'll need to set the decimal place to 2 by using toFixed()

This is just a solution of getting the number you want.

alert((2205.88 - 1103.01).toFixed(2));
YaBCK
  • 2,949
  • 4
  • 32
  • 61