显示我的用例的示例:
from __future__ import division
a = 215 / 4
print a # Case 1. Should print 53.75
a = 215 / 3
print a # Case 2. Should print 71.6666666666666714 i.e. decimal to 16 precision.
不起作用的可能解决方案:
print str(a) # Case 2 gets printed with only 12 precision (needed 16)
print repr(a) # Case 2 gets printed as 71.66666666666667 (precision 14, needed 16)
print '{0:.16f}'.format(a) # Case 1 gets printed with trailing zeroes
print '{0:.16g}'.format(a) # Decimal precision is 14, needed 16.
最好的蟒蛇解决方案是什么?
编辑:如果精度为16是float
除法的限制,那么获得8位小数精度的Python方法是什么。有比'{0:.8f}'.format(a).rstrip('0')
更好的解决方案吗?
我相信getcontext()将是您在十进制库中的朋友。
这允许您设置精度并操作重要数字结果。
https://docs.python.org/2/library/decimal.html