Python十进制.十进制-getcontext().prec设置和输出中的小数位数 [英] Python decimal.Decimal - getcontext().prec setting and number of decimals in output

查看:242
本文介绍了Python十进制.十进制-getcontext().prec设置和输出中的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对使用十进制.十进制转换的数字字符串进行算术运算.我希望返回的结果有两个小数,而不考虑转换后的数字字符串有多少个小数.

I want to do arithmetic with converted number strings using decimal.Decimal. I want the return to have two decimals regardless of the quantity of decimals the converted number strings have.

在这种特殊情况下,为什么两位十进制精度给我一个十进制收益,为什么三位数精度给我我想要的收益(2个十进制-> 2.15)

In this particular case, why does two decimal precision give me one decimal return and why does three decimal precision give me the return I want (2 decimals -> 2.15)

from decimal import *
getcontext().prec = 2
a = Decimal(x.replace(',','.'))
b = Decimal(y.replace(',','.'))
print(a), print(b), print(a-b)
>>> 2.60 0.45 2.2

getcontext().prec = 3
a = Decimal(x.replace(',','.'))
b = Decimal(y.replace(',','.'))
print(a, b, a-b)
>>> 2.60 0.45 2.15

推荐答案

getcontext().prec 设置 Decimal lib将用于返回任何数字的位数的精度计算得出的数字,即prec = 2将返回2个数字(first = 2,second = 2),在prec = 3中将显示三个数字(first = 2,second = 1,third = 5).

The getcontext().prec set the precision of digits which Decimal lib will use to return any calculated number, that is, prec = 2 will return 2 digits (first=2, second=2) and in prec = 3 that will show three numbers(first=2, second=1, third=5).

但是,这里有一个窍门.创建a和b变量时,小数用作精确度是您赋予它的数字的位数.您会看到只需在IDLE中调用a或b.

However , there is a trick here. When you created the a and b variables, the Decimal used as precision the amount of digits from the number you gave to it. You can see that just calling the a or the b in your IDLE.

这篇关于Python十进制.十进制-getcontext().prec设置和输出中的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆