Floating point representations seem to do integer arithmetic correctly - why?

前端 未结 8 1297
死守一世寂寞
死守一世寂寞 2021-01-06 10:41

I\'ve been playing around with floating point numbers a little bit, and based on what I\'ve learned about them in the past, the fact that 0.1 + 0.2 ends up bein

8条回答
  •  爱一瞬间的悲伤
    2021-01-06 11:06

    I'm writing that under assumption that Javascript uses double-precision floating-point representation for all numbers.

    Some numbers have an exact representation in the floating-point format, in particular, all integers such that |x| < 2^53. Some numbers don't, in particular, fractions such as 0.1 or 0.2 which become infinite fractions in binary representation.

    If all operands and the result of an operation have an exact representation, then it would be safe to compare the result using ==.

    Related questions:

    What number in binary can only be represented as an approximation?

    Why can't decimal numbers be represented exactly in binary?

提交回复
热议问题