0

When I multiply 3 * 1.1 in JavaScript instead of returning 3.3, it results in 3.30000000000000003, Why is this?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Weich92
  • 17
  • 3

1 Answers1

2

That's because numbers in computers are represented as floating point numbers, which have limited precision. Some operations will cause tiny errors and there's nothing you can do about that.

It's also a reason to never compare numbers using ==.

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • Thanks @cpacheco for translating into Spanish. – This company is turning evil. Nov 10 '14 at 13:05
  • So if we should not compare it by `==` , then what is the recommended way? – Ayush Kumar Jun 14 '21 at 05:46
  • @AyushKumar compare them to some tolerance: `a == b` becomes `Math.abs(a - b) < TOLERANCE`. What that tolerance is depends on context. Note that JS has the concept of "safe integers", which IIRC are up to [2^53](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER), so if you're only doing additions, subtractions, multiplications, or divisions of even integers, by integers, that result in values in that range, you can be sure they're the same and you can use `==`. – This company is turning evil. Jun 14 '21 at 14:16