0

Is there any explanation for this strange behavior tested on chrome, firefox, ie. when you do 8.9 * 3 you get 26.700000000000003

console.log(8.9 * 3);

any help?

  • see https://stackoverflow.com/questions/1458633 – Avocado May 02 '20 at 23:18
  • Programming is not math, you will have issues with numbers that are too big (overflow), too small (underflow), and numbers not precisely representable by IEEE 754 floats. It sucks, but it's something we all have to deal with. – Jared Smith May 02 '20 at 23:20

1 Answers1

0

You have discovered the "joy" of doing real number math in computers.

JavaScript uses 64-bit IEEE-754 numbers; this leaves 64 bits to represent all the possible real numbers that it knows about.

They are represented as what we call "floating point" numbers, which just means that the computer stores the characteristic (integer part) and the mantissa (fractional part) in those 64-bits. The integer part, to the left of the decimal, is easily dealt with. The mantissa is a bit trickier, and it is stored, basically as a fraction in binary.

Unfortunately, such binary fractions cannot always represent decimal quantities with 100% accuracy....and you have discovered one such case.

Wes
  • 950
  • 5
  • 12
  • 1
    To be fair, this isn't just a problem with Javascript (every popular language uses IEEE 754 floats), and it isn't just a problem with binary (e.g. 1/3 in base 10). It's the nature of number systems. – Jared Smith May 02 '20 at 23:26