Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中以最大精度打印十进制数而不带尾随零的最佳方法_Python_Format_Decimal_Repr - Fatal编程技术网

在Python中以最大精度打印十进制数而不带尾随零的最佳方法

在Python中以最大精度打印十进制数而不带尾随零的最佳方法,python,format,decimal,repr,Python,Format,Decimal,Repr,显示我的用例的示例: 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 pr

显示我的用例的示例:

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.
对于这个问题,最好的Python解决方案是什么

编辑:如果16的精度是
float
除法的限制,那么获得8位小数精度的python方法是什么。是否有比
'{0:.8f}.format(a).rstrip('0')
更好的解决方案?

我相信getcontext()将是您在十进制库中的朋友

这允许您设置精度并操纵重要的图形结果


精度实际上不是16位,因为正如您所看到的,它以
714结尾,这是不正确的。为什么要在浮点数实际上没有16位精度时显示16位数字?这是否意味着不可能获得18位有效数字(包括16位精度)使用浮点除法?18位有效数字完全不可能。我所说的精度是有效数字的数量,其中浮点数略低于16。如果你需要更有效的数字,考虑一下你的计算。本着编程的精神,我们这样做是因为我们可以。它不需要是实际的。如果他想知道怎么做,这就是他要问的地方。这只适用于使用
decimal.decimal
执行的计算,而这对显示精度没有任何影响。