Python float 到 int 的转换

时间:2022-11-29
本文介绍了Python float 到 int 的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我将浮点数转换为整数,但我并不总是有预期值.

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("--------- 251.0")
y = 251.0
print(y)
print(int(y))

print("--------- 2.51 * 100")
y = x * 100
print(y)
print(int(y))

print("--------- 2.51 * 1000 / 10")
y = x * 1000 / 10
print(y)
print(int(y))

print("--------- 2.51 * 100 * 10 / 10")
y = x * 100 * 10 / 10
print(y)
print(int(y))

x = 4.02
print("--------- 402.0")
y = 402.0
print(y)
print(int(y))

print("--------- 4.02 * 100")
y = x * 100
print(y)
print(int(y))

print("--------- 4.02 * 1000 / 10")
y = x * 1000 / 10
print(y)
print(int(y))

print("--------- 4.02 * 100 * 10 / 10")
y = x * 100 * 10 / 10
print(y)
print(int(y))

这是结果(第一个值是操作的结果,第二个值是相同操作的 int()):

And here's the result (first value is the result of the operation, second value is int() of the same operation):

--------- 251.0
251.0
251
--------- 2.51 * 100
251.0
250
--------- 2.51 * 1000 / 10
251.0
251
--------- 2.51 * 100 * 10 / 10
251.0
250
--------- 402.0
402.0
402
--------- 4.02 * 100
402.0
401
--------- 4.02 * 1000 / 10
402.0
401
--------- 4.02 * 100 * 10 / 10
402.0
401

2.51 和 4.02 是导致 2.50 -> 5.00 范围内奇怪行为的唯一值.当给定相同的操作时,该范围内的每隔两个数字值转换为 int 没有任何问题.

2.51 and 4.02 are the only values that lead to that strange behaviour on the 2.50 -> 5.00 range. Every other two digits value in that range converts to int without any problem when given the same operations.

那么,我错过了什么导致这些结果?顺便说一下,我使用的是 Python 2.7.2.

So, what am I missing that leads to those results? I'm using Python 2.7.2 by the way.

推荐答案

2.51 * 100 = 250.999999999997

int() 函数只是截断小数点处的数字,得到 250.使用

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100)) 

获取 251 作为整数.一般来说,浮点数不能精确表示.因此,应注意舍入误差.如前所述,这不是 Python 特有的问题.这是所有计算机语言中反复出现的问题.

to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

这篇关于Python float 到 int 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Python中小数点后的浮点数加零 下一篇:Pandas 读取具有浮点值的 csv 文件会导致奇怪的舍

相关文章

最新文章