这是我的代码:
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 ?我将使用结果作为字符串。
当前回答
这对任何指数都适用:
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
其他回答
'%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'
我也遇到过类似的问题,用我的解决方案:
from decimal import Decimal
Decimal(2/25500)
#output:0.00007843137254901961000728982664753630160703323781490325927734375
如果它是一个字符串,那么使用内置的float对其进行转换,例如: 打印(“%。5f" %浮动("1.43572 -03")) 答案:0.00143572
除了SG的答案,你还可以使用Decimal模块:
from decimal import Decimal
x = str(Decimal(1) / Decimal(10000))
# x is a string '0.0001'