Python的舍入问题 [英] Rounding Problem with Python
问题描述
可能的重复:
浮点数的 Python 舍入错误
我在 Python 中有一个舍入问题.如果我计算
I have a rounding Problem in Python. If i calculate
32.50 * 0.19 = 6.1749999999999998
32.50 * 0.19 = 6.1749999999999998
但这应该是 6.175.如果我将 6.1749999999999998 舍入到小数点后两位,它会正确显示 6.18.所以我可以忍受.
But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.
但是如果我计算这个:
32.50 * 0.19 * 3 = 18.524999999999999
32.50 * 0.19 * 3 = 18.524999999999999
这应该是 18.525.如果我将值 18.524999999999999 舍入两位小数,则显示为 18.52.
This should be 18.525. If i round the value 18.524999999999999 with two decimal places it shows 18.52.
它应该显示我 18.53.我做错了什么,我该如何解决?
It should show me 18.53. What am i doing wrong and how can i fix it ?
推荐答案
如果你需要精确的算术,你可以使用 十进制 模块:
If you need exact arithmetic, you could use the decimal module:
import decimal
D=decimal.Decimal
x=D('32.50')*D('0.19')
print(x)
# 6.1750
print(x.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 6.18
y=D('32.50')*D('0.19')*D('3')
print(y)
# 18.5250
print(y.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 18.53
这篇关于Python的舍入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!