Python float to int conversion

前端 未结 5 1036
南笙
南笙 2020-11-28 09:13

Basically, I\'m converting a float to an int, but I don\'t always have the expected value.

Here\'s the code I\'m executing:

x = 2.51

print(\"         


        
5条回答
  •  误落风尘
    2020-11-28 09:36

    Languages that use binary floating point representations (Python is one) cannot represent all fractional values exactly. If the result of your calculation is 250.99999999999 (and it might be), then taking the integer part will result in 250.

    A canonical article on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

提交回复
热议问题