Why 6.84 - 3.6 == 3.2399999999999998

前端 未结 7 739
星月不相逢
星月不相逢 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

    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.

提交回复
热议问题