这是我的代码:

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

其他回答

这对任何指数都适用:

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

在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'
'%f' % (x/y)

但你自己也需要控制精度。例如,

'%f' % (1/10**8)

将只显示0。 细节在文档中

或者对于python3,使用等效的旧格式或新样式格式

另一种选择是,如果你正在使用熊猫,并且想要压制所有浮点数的科学计数法,是调整熊猫选项。

import pandas as pd
pd.options.display.float_format = '{:.2f}'.format