-3

Possible Duplicate:
Is JavaScript's Math broken?

I have just started playing around with Javascript in the last couple of days and I have noticed something that appears to be quite peculiar. When I add some numbers together, I end up with a marginally incorrect answer.

4.99 + 0.98 = 5.970000000000001

Why does this happen?

Community
  • 1
  • 1
inperspective
  • 1,854
  • 1
  • 19
  • 21

2 Answers2

7

I invite you to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • It's a lot to know... it should be called "What A Computer Scientist **Could** Know About Floating-Point Arithmetic" – gdoron Feb 22 '12 at 12:16
0

You can use sprintf like this:

console.log(sprintf("%.2f", (4.99 + 0.98))); // 5.97
Sarfraz
  • 377,238
  • 77
  • 533
  • 578