这是我的代码:

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

其他回答

这是黄瓜船长的答案,但有两个补充。

1)允许函数获得非科学表示法的数字,并按原样返回它们(因此您可以抛出大量输入,其中一些数字是0.00003123 vs 3.123e-05,但函数仍然可以工作。

2)增加对负数的支持。(在原始函数中,负数将从-1.08904e-05变为0.0000-108904)

def getExpandedScientificNotation(flt):
    was_neg = False
    if not ("e" in flt):
        return flt
    if flt.startswith('-'):
        flt = flt[1:]
        was_neg = True 
    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('.', '')
    if was_neg:
        return_val='-'+return_val
    return return_val

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

import pandas as pd
pd.options.display.float_format = '{:.2f}'.format
'%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'

如果它是一个字符串,那么使用内置的float对其进行转换,例如: 打印(“%。5f" %浮动("1.43572 -03")) 答案:0.00143572