使用标准库Decimal将运算符应用于非常长的十进制数时,禁止使用科学计数法

时间:2016-03-16 15:15:26

标签: python decimal

使用标准库'十进制'给出两个字符串:

import decimal
value1 = "992389829398023985092982398023923023.32598203985902"
value2 = "138582939807398509298239235233.3259822352359235203952093"

单独地可以评估字符串并保留小数:

>>>> decimal.Decimal(value1)
Decimal("992389829398023985092982398023923023.32598203985902")
>>>> decimal.Decimal(value2)
Decima2("138582939807398509298239235233.3259822352359235203952093")

应用运算符后,结果将转换为科学计数法,并且精度会丢失:

>>>> decimal.Decimal(value1) - decimal.Decimal(value2)
Decimal('9.923896908150841776944730998E+35')

格式化小数精度不会保留十进制值:

>>>> print("%.40f" % (decimal.Decimal(value1)-decimal.Decimal(value2)))
992389690815084186020235597584531456.0000000000000000000000000000000000000000

如何对非常大的小数进行操作,同时保持小数精度的完整性,还能抑制科学记数法?

1 个答案:

答案 0 :(得分:1)

尝试使用context设置精度:

import decimal
from decimal import localcontext
value1 = "992389829398023985092982398023923023.32598203985902"
value2 = "138582939807398509298239235233.3259822352359235203952093"


with localcontext() as ctx:
    #your desired precision in # of digits
    ctx.prec = 100
    print("{:.40f}".format(decimal.Decimal(value1) - decimal.Decimal(value2)))

或只是设置全局值:

decimal.getcontext().prec = 100
print("{:.40f}".format(decimal.Decimal(value1) - decimal.Decimal(value2)))

输出:

992389690815084177694473099784687789.9999998046230964796047907000000000000000

或打印声明(即decimal.Decimal(value1) - decimal.Decimal(value2)):

Decimal('992389690815084177694473099784687789.9999998046230964796047907')