1

As far as I know, 2 + 2 + 2 is the same thing as 2 * 3. The result of both is 6. Why it's not like that in JS?

let result = 0;
for (let i = 0; i < 50; i++) {
   result += 0.2; //addition
};
console.log(result);

console.log(0.2 * 50); //multiplication

Is there some difference in execution between addition and multiplication in JS? What the cause of this behaviour?

Ivan
  • 478
  • 2
  • 13
  • 2
    https://floating-point-gui.de/ – sp00m Aug 16 '21 at 09:46
  • same goes for `0.3 + 0.6` you'd expect `0.9` but get `0.89999999`. Most of the time you'll end up using `floor()` or `ceil()` – ahsan Aug 16 '21 at 09:48
  • @Ahsan Khan I know that floating numbers are horrible in math operations. But as I see, it extends only to addition. Why it doesn't extend to multiplication too? – Ivan Aug 16 '21 at 09:52
  • Relevant: [What tricks does JS employ to show/caclulate floating point numbers](https://stackoverflow.com/q/68482867) – VLAZ Aug 16 '21 at 10:02
  • 1
    @Ivan it does extend to multiplication too, it depends on the numbers, for ex `0.2 * 3` gives `0.6000000000000001`. – sp00m Aug 16 '21 at 10:06

0 Answers0