3
'-15.48' - '43'

Just wrote this in console and result is the following:

-58.480000000000004

Why Is it so? And what to do to get correct result?

user2950593
  • 9,233
  • 15
  • 67
  • 131

3 Answers3

3

Because all floating point math is like this and is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double.

to fix it you may try:

(-15.48 - 43).toFixed(2);

Fiddle demo

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

use: toFixed()

var num = 5.56789;
var n=num.toFixed(2);

result:5.57
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
0

http://en.wikipedia.org/wiki/Machine_epsilon

Humans count in decimal numbers, machines mostly use binary. 10 == 2x5; 2 and 5 are mutually prime numbers. That trivial fact has an unpleasant consequence though.

  • In most calculations (except lucky degenerate cases) with "simple" decimal numbers, that include division, the result would be an indefinite repeating binary number.
  • In most calculations (except lucky degenerate cases) with "simple" binary numbers, that include division, the result would be an indefinite repeating decimal number.

One can check this using pen and pencil as described http://en.wikipedia.org/wiki/Repeating_decimal#Every_rational_number_is_either_a_terminating_or_repeating_decimal

  • That means that almost every time you see the the result of floating point calculations on your screen - as a finite number - the computer somewhat cheats at you and shows you some approximation instead of the real result.
  • That means that almost every time you store the results of the calculation in the variable - which has a finite size, not any larger than the computer's available memory - the computer somewhat cheats at you and retains some approximation instead of the real result.

The typical gotchas then may include.

  • Program is accounting for the sum of some looong sequence, an infinite loop of x AVG := AVG + X[i]; kind where 0 < X[i] < const. If the loop would run long enough, you would see that at some point AVG no more changes the value, all the elements fro mthatpoint further on are just discarded.
  • Program calculates some value twice using different formulas and then makes a safety check like Value_1 == Value_2. For theoretical mathematics the values are equal, for the real computers they are not.
Arioch 'The
  • 15,799
  • 35
  • 62