Python小数精度和舍入

时间:2016-08-12 07:42:57

标签: python decimal rounding

我想限制浮点数的精度,并将其作为下一步操作的精确值,但我对十进制模块做错了。

from decimal import *

factor = 350/float(255)

# Settings
getcontext().prec = 1
getcontext().rounding = ROUND_UP

print Decimal(factor)

Python输出: 1.372549019607843145962533526471816003322601318359375

预期和想要的结果:1.4

1 个答案:

答案 0 :(得分:0)

来自Python文档:(https://docs.python.org/2/library/decimal.html

新十进制的重要性仅由输入的位数决定。上下文精度和舍入仅在算术运算期间发挥作用

getcontext().prec = 6
Decimal('3.0')
Decimal('3.0')
Decimal('3.1415926535')
Decimal('3.1415926535')
Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
getcontext().rounding = ROUND_UP
Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

所以你需要在操作中使用小数,而不是在打印结果时。

相关问题