这是我的代码:
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 ?我将使用结果作为字符串。
当前回答
在Python的新版本(2.6及更高版本)中,你可以使用" .format()来完成@SilentGhost建议的事情:
'{0:f}'.format(x/y)
其他回答
'%f' % (x/y)
但你自己也需要控制精度。例如,
'%f' % (1/10**8)
将只显示0。 细节在文档中
或者对于python3,使用等效的旧格式或新样式格式
您可以使用内置的格式化功能。
>>> a = -3.42142141234123e-15
>>> format(a, 'f')
'-0.000000'
>>> format(a, '.50f') # Or you can specify precision
'-0.00000000000000342142141234122994048466990874926279'
从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确实需要浮点数输入,因此需要强制转换。
除了SG的答案,你还可以使用Decimal模块:
from decimal import Decimal
x = str(Decimal(1) / Decimal(10000))
# x is a string '0.0001'
对于numpy数组,可以使用suppress命令as进行抑制
import numpy as np
np.set_printoptions(suppress=True)