【发布时间】:2018-03-13 16:37:49
【问题描述】:
我对 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 函数SO Link 将值转换为字符串并截断。
3. 我尝试截断到小数点后 17 位,然后除以 100,但没有成功。
【问题讨论】:
-
"vol = Decimal(39.992)" 你已经输了。
vol = Decimal('39.992')
标签: python python-2.7 decimal