关于浮点数:如何抑制Python中的科学计数法?

How do I suppress scientific notation in Python?

这是我的代码:

1
2
3
x = 1.0
y = 100000.0    
print x/y

我的商显示为1.00000e-05

有什么方法可以抑制科学计数法并使其显示为
0.00001? 我将使用结果作为字符串。


使用较新的版本''.format(还要记住指定要显示在.之后的位数,这取决于浮点数是多少)。请参阅以下示例:

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

如上图所示,默认值为6位!这对我们的案例没有帮助,因此我们可以使用类似以下的内容:

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

更新资料

从Python 3.6开始,可以使用新的格式化字符串文字来简化此过程,如下所示:

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


1
'%f' % (x/y)

但是您需要自己管理精度。例如。,

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

将仅显示零。
详细信息在文档中

或对于Python 3,等效的旧格式或新样式格式


使用较新版本的Python(2.6和更高版本),您可以使用''.format()完成@SilentGhost建议的操作:

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


如果您使用的是熊猫并且想抑制所有浮标的科学计数法,则另一种选择是调整熊猫选项。

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

这是使用Cucumber上尉的答案,但有2个补充。

1)允许函数获取非科学计数法数字并按原样返回它们(因此您可以输入很多数字,其中一些数字为0.00003123与3.123e-05,并且仍然可以正常工作。

2)添加了对负数的支持。 (在原始功能中,负数最终会从-1.08904e-05变为0.0000-108904)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

这将适用于任何指数:

1
2
3
4
5
6
7
8
9
10
11
12
13
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


如果它是string,则使用其上的内置float进行转换:
print("%.5f" % float("1.43572e-03"))
答案:0.00143572


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

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

# x is a string '0.0001'


上面的大多数答案都要求您指定精度。但是,如果要显示这样的浮点数,而没有不必要的零,该怎么办:

1
2
3
4
5
6
7
8
1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001

numpy有一个答案:np.format_float_positional

1
2
3
4
import numpy as np

def format_float(num):
    return np.format_float_positional(num, trim='-')

从3.6版本开始(可能也适用于稍旧的3.x版本),这是我的解决方案:

1
2
3
4
5
6
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')

precision计算的目的是确保我们具有足够的精度,以免超出科学计数法(默认精度仍为6)。

dec_precision参数增加了用于小数点的精度。由于这使用了n格式,因此不会添加不重要的零(与f格式不同)。 n还将处理呈现不带小数点的舍入整数。

n确实需要float输入,因此需要强制转换。


由于这是在Google上的最佳结果,因此在找不到解决方案后,我将在此处发布。如果要格式化浮动对象的显示值并使它保持浮动(而不是字符串),则可以使用以下解决方案:

创建一个新的类,该类修改浮点值的显示方式。

1
2
3
4
5
from builtins import float
class FormattedFloat(float):

    def __str__(self):
        return"{:.10f}".format(self).rstrip('0')

您可以通过更改{:f}中的整数值自己修改精度。


使用3.6.4时,我遇到类似的问题,即随机使用此命令时,输出文件中的数字将以科学计数法进行格式化:

1
fout.write('someFloats: {0:0.8},{1:0.8},{2:0.8}'.format(someFloat[0], someFloat[1], someFloat[2]))

我要做的就是添加'f':

1
fout.write('someFloats: {0:0.8f},{1:0.8f},{2:0.8f}'.format(someFloat[0], someFloat[1], someFloat[2]))