-2

Why 'divide' arithmetic calcualtion for 0.6 / 0.2 = 2.9999999999999996 gives javascript function, instead of 3

1 Answers1

3

Because in binary, 0.6 is not exactly 0.6, and 0.2 is not exactly 0.2.

"Not exactly 0.6" / "Not exactly 0.2" = "Not exactly 3"


In computers, all numbers are represented in binary. When you write 0.6, the computer actually stores...

1/2 + 1/16 + 1/32 + 1/256 + ...

Similarly for 0.2:

1/8 + 1/16 + 1/128 + 1/256 + ...

Consequently, you get a result along the lines of diving all those items, which comes out to something that is almost, but not quite, entirely unlike 3.

Consider working with integers only if possible.


Further edit: You can actually observe this in the browser's console.

console

You see? the result of the division is extremely close to, but not exactly the expected answer.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540