0

Why is it if I do this in javascript, I get the following result:

1234.56 * 10 = 12345.599999999999

It should be 123456. How can I get around this problem?

Thanks.

Esailija
  • 138,174
  • 23
  • 272
  • 326
Mike
  • 23
  • 1
  • 5

4 Answers4

3

Another easy solution:

parseFloat((1234.56 * 10).toPrecision(12))

and the result will be: 12345.6, and YES... it works with decimal numbers.

mzalazar
  • 6,206
  • 3
  • 34
  • 31
3

Floating points are not exact, since there are ifinite numbers at their range [or in any range to be more exact], and only a finite number of bits to store this data.

Have a look at what every programmer should know about floating point arithmetics.

amit
  • 175,853
  • 27
  • 231
  • 333
1

As the others said, floating points and so on.

Easy solution would be to do something like this:

var answer = parseInt(1234.56 * 10);

Or just use Math.round?

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

All numbers in JS are internally defined by float and drop the less significant digits if needed.

(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true

And javascript is well known for droping bits quite often in numbers. So handle with care

fmsf
  • 36,317
  • 49
  • 147
  • 195