0

Why in javascript 0.95-0.05 = 0.8999999999999999? How can make = 0.90?

I discovered this into a complex app, but to reproduce it's possible to simply put the operation in the browser console.

Davide C
  • 830
  • 2
  • 11
  • 21
  • Well, js is kinda especial with numbers, specially floating numbers. You can try `console.log(0.1 + 0.2)` to see what Im talking about haha – Osakr Nov 10 '22 at 15:45
  • You could always move the decimal over, round, and move it back: `Math.round(((0.95 - 0.05) * 1e15)) / 1e15`; See: [example](https://pastebin.com/QJYb3JF9) – Mr. Polywhirl Nov 10 '22 at 15:46
  • You have more information about this float behavior https://www.codemag.com/article/1811041/JavaScript-Corner-Math-and-the-Pitfalls-of-Floating-Point-Numbers – Osakr Nov 10 '22 at 15:46
  • You can check this thread https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Nick Vu Nov 10 '22 at 15:47
  • 1
    As a general rule, don't use vanilla JS math for anything that requires significant precision (It does the job 99% of the time, but you do not want it handling e.g. your banking software) – DBS Nov 10 '22 at 15:49
  • 1
    This has nothing to do with Javascript, it's how floating point works in all languages that use IEEE 754 floating point, and that's pretty much all popular languages. – Keith Nov 10 '22 at 15:55

0 Answers0