python - python中float的int()转换

标签 python python-2.6

我在下面的代码中将 float 转换为整数。但是,生成的输出对于镍来说是不正确的。

代码:

actual = 25
paid = 26.65
cents = (paid-actual)*100
quarters = int(cents/25)
cents = cents %25
dimes = int(cents/10)
cents = cents %10
nickels = int(cents/5)
print quarters, dimes, nickels,cents
print 5.0/5,int(5.0/5)

输出:

6 1 0 5.0
1.0 1

预期输出

6 1 1 5.0
1.0 1

如果我明确地执行 int(5.0/5) 我得到 1 ,但是当同样的操作分配给我代码中的变量时,我得到 0 。我不确定为什么。谁能解释一下?

最佳答案

float 不能保证与您期望的数字一致,它们可能几乎没有偏离,比如 5.0 实际上可能是 4.999... 并且由于int() 截断/舍入,你会得到你的错误。

许多银行完全放弃了 float 问题,只使用 $1.00 = 100 我建议您也这样做,如下所示:

actual = 25
paid = 26.65
cents = int(round(paid*100)) #Turns 26.65 into 2665 before you do any float math
dollars = cents / 100
cents %= 100
quarters = cents / 25
cents %= 25
dimes = cents / 10
cents %= 10
nickels = cents / 5
print quarters, dimes, nickels,cents
print 5.0/5,int(5.0/5)

请注意,这会输出 2 1 1 5,因为那是 2 个季度、1 个角钱和 1 个镍币 = $.65

通常您希望尽可能晚地舍入以保持精度,但是当您处理金钱时,我认为完全使用整数会使 float 的噩梦消失得更快。

此外,由于您使用的是 2.6,因此您需要转换为 int(),因为 round() 直到 3.1 才返回整数

关于python - python中float的int()转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17824639/

相关文章:

python - scikit-learn 的 LogisticRegression() 能否自动将输入数据标准化为 z 分数?

python - 为什么 __dir__() 不适用于 python 中的模块?

python - 从包含 key=value 的字符串构建字典

python - sys.stdout.writelines ("hello")和 sys.stdout.write ("hello")

python - 导入前安装模块

python - 如何使用Python中另一列的值填充pandas数据框中的空值?

html - 仅使用 id 启用复选框

python - 你如何在 python 2 和 3 之间切换,反之亦然?

python - 如何从代码中随机选择一行而不重复

python - 如何使用 Python 识别 Windows 10?