0

who can tell me why:

console.log(4 - 1)
console.log(4.2 - 1)
console.log(4.01 - 1)

But:

console.log(4.1 - 1)
console.log(4.02 - 1)

Tried with parseFloat - same issue

Was able to get the desired result with number.toFixed(2). Still, where is that decimal coming from.

Whats the JS explanation for this?

Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
Jony-Y
  • 1,579
  • 1
  • 13
  • 30
  • This happens because 0.1, in binary, is a tithe. That's why Java and some other languages use some high precision classes, such as `BigDecimal` – Leonardo Alves Machado Apr 10 '19 at 13:36
  • Please see here for a great article on floating point issues and limitations: https://docs.python.org/3/tutorial/floatingpoint.html –  Apr 10 '19 at 13:37
  • @LeonardoAlvesMachado What is the definition of `tithe` in the context of computation? –  Apr 10 '19 at 13:38
  • @Amy - maybe I mistranslated what I mean by tithe. Here is the definition from [Wolfram](http://mathworld.wolfram.com/PeriodicContinuedFraction.html): _A periodic continued fraction is a continued fraction (generally a regular continued fraction) whose terms eventually repeat from some point onwards._ – Leonardo Alves Machado Apr 10 '19 at 13:41
  • @LeonardoAlvesMachado Ah, that makes sense then. In English, a "tithe" is 1/10th of your earnings paid to a church as tribute. I'm not aware of any other definitions. Hence my confusion. –  Apr 10 '19 at 13:46
  • @Amy - Thanks, it was a great read. Had No idea. – Jony-Y Apr 10 '19 at 13:49
  • @Amy Bad Google Translator XD... Thanks for the information – Leonardo Alves Machado Apr 10 '19 at 13:51

0 Answers0