这是我的代码:

x = 1.0
y = 100000.0    
print x/y

我的商显示为1.00000e-05。

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


当前回答

'%f' % (x/y)

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

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

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

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

其他回答

这对任何指数都适用:

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

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

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

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

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

更新

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

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

从3.6开始(可能适用于稍微老一点的3。X也是),这是我的解决方案:

import locale
locale.setlocale(locale.LC_ALL, '')

def number_format(n, dec_precision=4):
    precision = len(str(round(n))) + dec_precision
    return format(float(n), f'.{precision}n')

精度计算的目的是确保我们有足够的精度来避免科学计数法(默认精度仍然是6)。

dec_precision参数增加了用于小数点的额外精度。由于这使用了n格式,因此不会添加无关紧要的零(与f格式不同)。N还将负责呈现不带小数的整数。

N确实需要浮点数输入,因此需要强制转换。

使用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]))

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