这是我的代码:

x = 1.0
y = 100000.0    
print x/y

我的商显示为1.00000e-05。

有没有办法压制科学符号,让它显示为 0.00001 ?我将使用结果作为字符串。


当前回答

在Python的新版本(2.6及更高版本)中,你可以使用" .format()来完成@SilentGhost建议的事情:

'{0:f}'.format(x/y)

其他回答

在Python的新版本(2.6及更高版本)中,你可以使用" .format()来完成@SilentGhost建议的事情:

'{0:f}'.format(x/y)

除了SG的答案,你还可以使用Decimal模块:

from decimal import Decimal
x = str(Decimal(1) / Decimal(10000))

# x is a string '0.0001'

使用新版本”。格式(还记得指定后面有多少位数字。你希望显示的,这取决于浮点数有多小)。请看这个例子:

>>> a = -7.1855143557448603e-17
>>> '{:f}'.format(a)
'-0.000000'

如上所示,默认是6位数!这对我们的案例没有帮助,所以我们可以使用这样的代码:

>>> '{:.20f}'.format(a)
'-0.00000000000000007186'

更新

从Python 3.6开始,可以使用新的格式化字符串字面值进行简化,如下所示:

>>> f'{a:.20f}'
'-0.00000000000000007186'

我也遇到过类似的问题,用我的解决方案:

from decimal import Decimal

Decimal(2/25500)
#output:0.00007843137254901961000728982664753630160703323781490325927734375

这对任何指数都适用:

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