这是我的代码:
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 ?我将使用结果作为字符串。
当前回答
上面的大多数答案都要求您指定精度。但是如果你想像这样显示浮点数,没有不必要的零呢:
1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001
Numpy给出了答案:np.format_float_positional
import numpy as np
def format_float(num):
return np.format_float_positional(num, trim='-')
其他回答
您可以使用内置的格式化功能。
>>> a = -3.42142141234123e-15
>>> format(a, 'f')
'-0.000000'
>>> format(a, '.50f') # Or you can specify precision
'-0.00000000000000342142141234122994048466990874926279'
使用3.6.4时,我遇到了一个类似的问题,当使用这个时,输出文件中的一个数字将被科学符号格式化:
fout.write('someFloats: {0:0.8},{1:0.8},{2:0.8}'.format(someFloat[0], someFloat[1], someFloat[2]))
我所要做的就是添加'f'来修复它:
fout.write('someFloats: {0:0.8f},{1:0.8f},{2:0.8f}'.format(someFloat[0], someFloat[1], someFloat[2]))
这对任何指数都适用:
def getExpandedScientificNotation(flt):
str_vals = str(flt).split('e')
coef = float(str_vals[0])
exp = int(str_vals[1])
return_val = ''
if int(exp) > 0:
return_val += str(coef).replace('.', '')
return_val += ''.join(['0' for _ in range(0, abs(exp - len(str(coef).split('.')[1])))])
elif int(exp) < 0:
return_val += '0.'
return_val += ''.join(['0' for _ in range(0, abs(exp) - 1)])
return_val += str(coef).replace('.', '')
return return_val
如果它是一个字符串,那么使用内置的float对其进行转换,例如: 打印(“%。5f" %浮动("1.43572 -03")) 答案:0.00143572
在Python的新版本(2.6及更高版本)中,你可以使用" .format()来完成@SilentGhost建议的事情:
'{0:f}'.format(x/y)