这是我的代码:
x = 1.0
y = 100000.0
print x/y
我的商显示为1.00000e-05。
有没有办法压制科学符号,让它显示为 0.00001 ?我将使用结果作为字符串。
这是我的代码:
x = 1.0
y = 100000.0
print x/y
我的商显示为1.00000e-05。
有没有办法压制科学符号,让它显示为 0.00001 ?我将使用结果作为字符串。
当前回答
将浮点数显示为任意数量的有效数字的更简单解决方案。这里不需要numpy或列表推导式:
def sig(num, digits=3):
"Return number formatted for significant digits"
if num == 0:
return 0
negative = '-' if num < 0 else ''
num = abs(float(num))
power = math.log(num, 10)
if num < 1:
step = int(10**(-int(power) + digits) * num)
return negative + '0.' + '0' * -int(power) + str(int(step)).rstrip('0')
elif power < digits - 1:
return negative + ('{0:.' + str(digits) + 'g}').format(num)
else:
return negative + str(int(num))
在示例中,我去掉了后面的0并显示完整的整数:sig(31415.9) = 31415而不是31400。如果您不喜欢修改代码,请随意修改。
测试:
for power in range(-8,8):
num = math.pi * 10**power
print(str(num).ljust(25), sig(num))
其他回答
我也遇到过类似的问题,用我的解决方案:
from decimal import Decimal
Decimal(2/25500)
#output:0.00007843137254901961000728982664753630160703323781490325927734375
从3.6开始(可能适用于稍微老一点的3。X也是),这是我的解决方案:
import locale
locale.setlocale(locale.LC_ALL, '')
def number_format(n, dec_precision=4):
precision = len(str(round(n))) + dec_precision
return format(float(n), f'.{precision}n')
精度计算的目的是确保我们有足够的精度来避免科学计数法(默认精度仍然是6)。
dec_precision参数增加了用于小数点的额外精度。由于这使用了n格式,因此不会添加无关紧要的零(与f格式不同)。N还将负责呈现不带小数的整数。
N确实需要浮点数输入,因此需要强制转换。
在Python的新版本(2.6及更高版本)中,你可以使用" .format()来完成@SilentGhost建议的事情:
'{0:f}'.format(x/y)
对于numpy数组,可以使用suppress命令as进行抑制
import numpy as np
np.set_printoptions(suppress=True)
'%f' % (x/y)
但你自己也需要控制精度。例如,
'%f' % (1/10**8)
将只显示0。 细节在文档中
或者对于python3,使用等效的旧格式或新样式格式