处理高精度小数

时间:2017-10-02 15:11:14

标签: python python-2.7 decimal

我是python的新手,我必须执行python代码的唯一原因是因为JavaScript的32位数字的限制。

情况:
我必须计算以下最大比例为38,精确度为19小数位数。 [MSSQL Ref: DECIMAL(38,19)]

数学运算: ((39.992 * 0.0000467788) * 0.02 / 100)

代码:

from decimal import *
import math

def truncate(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d+'0'*n)[:n]])

getcontext().prec = 28

expectedTotal = "0.0000003741555539199"

vol = Decimal(39.992)
rate = Decimal(0.0000467788)
percent = Decimal(0.02)

cal1 = Decimal(truncate(((vol) * rate * percent),19))
print("(vol * rate * percent) at 19 decimal places: {}".format(cal1))

total = Decimal((vol * rate) * percent / 100)
print("total that I get: {}".format(total))
print("total that I want: {}".format(expectedTotal))

结果:

(vol * rate * percent) at 19 decimal places: 0.0000374155553919999
total that I get: 3.74155553919999983602300172E-7
total that I want: 0.0000003741555539199

点数:
1.我对小数点后19位以外的准确度没有用处 2. truncate function SO Link将value转换为string并截断 3.我尝试截断到17位小数,然后除以100,但没有用。

1 个答案:

答案 0 :(得分:1)

你可以在Python中压制科学记数法:

x = 3.74155553919999983602300172E-7
print('{:f}'.format(x))
>> 0.000000
print('{:.20f}'.format(x))
>> 0.00000037415555392000

请注意,默认精度为6但是在示例情况下是不够的,因此您可以像在第二次测试中那样表达您的精度。

注意:如果你设置一个特定的数字,如果需要,Python将在末尾用零填充。