Why 6.84 - 3.6 == 3.2399999999999998

前端 未结 7 665
星月不相逢
星月不相逢 2020-12-22 03:13

I just encountered this and can\'t figure out why exactly Ruby behaves this way.

Could someone explain why in Ruby:

6.84 - 3.6 == 3.2399999999999998
         


        
相关标签:
7条回答
  • 2020-12-22 03:34

    0.01 or 0.07 cannot be precisely represented in binary floating-point.

    0 讨论(0)
  • 2020-12-22 03:34

    Floating point uses an internal representation that's inherently imprecise. You should always round down your answers for display purposes:

    '%.4f' % (6.84 - 3.6)
    # => "3.2400"
    

    Left to its own devices, Ruby, like many other languages, will express floating point numbers to a ridiculous degree of precision.

    0 讨论(0)
  • 2020-12-22 03:35

    It's a binary floating-point problem.

    read this

    0 讨论(0)
  • 2020-12-22 03:42

    Base notation-2 and decimal base is used by double and float

    0 讨论(0)
  • 2020-12-22 03:43

    Because double/float use base-2 notation and decimal base-10 notation.

    Here's a useful link: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

    0 讨论(0)
  • 2020-12-22 03:45

    See the answers in "Why is the 100*0.07 equal to 6.9999....?" (and many other places) about floating-point math.

    Why is the 100*0.07 equal to 6.9999....?

    0 讨论(0)
提交回复
热议问题