第五章:数学运算-decimal:定点数和浮点数的数学运算-上下文-各实例的上下文

5.1.5.5 各实例的上下文
还可以用上下文构造Decimal实例,然后从这个上下文继承精度以及转换的取整参数。

import decimal

# Set up a context with limited precision.
c = decimal.getcontext().copy()
c.prec = 3

# Create our constant.
pi = c.create_decimal('3.1415')

# The constant value is rounded off.
print('PI    :',pi)

# The result of using the constant uses the global context.
print('RESULT:',decimal.Decimal('2.01') * pi)

例如,这样一来,应用就可以选择与用户数据精度不同的常量值精度。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/87949336