打印浮点数时如何抑制科学计数法?

问题:打印浮点数时如何抑制科学计数法?

这是我的代码:

x = 1.0
y = 100000.0    
print x/y

我的商显示为1.00000e-05

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

Here’s my code:

x = 1.0
y = 100000.0    
print x/y

My quotient displays as 1.00000e-05.

Is there any way to suppress scientific notation and make it display as 0.00001? I’m going to use the result as a string.


回答 0

'%f' % (x/y)

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

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

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

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

'%f' % (x/y)

but you need to manage precision yourself. e.g.,

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

will display zeros only.
details are in the docs

Or for Python 3 the equivalent old formatting or the newer style formatting


回答 1

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

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

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

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

更新资料

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

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

Using the newer version ''.format (also remember to specify how many digit after the . you wish to display, this depends on how small is the floating number). See this example:

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

as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this:

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

Update

Starting in Python 3.6, this can be simplified with the new formatted string literal, as follows:

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

回答 2

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

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

With newer versions of Python (2.6 and later), you can use ''.format() to accomplish what @SilentGhost suggested:

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

回答 3

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

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

Another option, if you are using pandas and would like to suppress scientific notation for all floats, is to adjust the pandas options.

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

回答 4

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

1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001

numpy 有一个答案: np.format_float_positional

import numpy as np

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

Most of the answers above require you to specify precision. But what if you want to display floats like this, with no unnecessary zeros:

1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001

numpy has an answer: np.format_float_positional

import numpy as np

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

回答 5

这将适用于任何指数:

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

This will work for any exponent:

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

回答 6

这是使用黄瓜队长的答案,但有2个补充。

1)允许函数获取非科学计数法数字并按原样返回它们(因此,您可以输入很多数字,其中某些数字为0.00003123与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

This is using Captain Cucumber’s answer, but with 2 additions.

1) allowing the function to get non scientific notation numbers and just return them as is (so you can throw a lot of input that some of the numbers are 0.00003123 vs 3.123e-05 and still have function work.

2) added support for negative numbers. (in original function, a negative number would end up like 0.0000-108904 from -1.08904e-05)

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

回答 7

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

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

# x is a string '0.0001'

In addition to SG’s answer, you can also use the Decimal module:

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

# x is a string '0.0001'

回答 8

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

If it is a string then use the built in float on it to do the conversion for instance: print( "%.5f" % float("1.43572e-03")) answer:0.00143572


回答 9

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

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

from builtins import float
class FormattedFloat(float):

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

您可以自己更改精度,方法是更改 {:f}

Since this is the top result on Google, I will post here after failing to find a solution for my problem. If you are looking to format the display value of a float object and have it remain a float – not a string, you can use this solution:

Create a new class that modifies the way that float values are displayed.

from builtins import float
class FormattedFloat(float):

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

You can modify the precision yourself by changing the integer values in {:f}


回答 10

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

Using 3.6.4, I was having a similar problem that randomly, a number in the output file would be formatted with scientific notation when using this:

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

All that I had to do to fix it was to add ‘f’:

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

回答 11

从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')

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

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

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

As of 3.6 (probably works with slightly older 3.x as well), this is my solution:

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')

The purpose of the precision calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).

The dec_precision argument adds additional precision to use for decimal points. Since this makes use of the n format, no insignificant zeros will be added (unlike f formats). n also will take care of rendering already-round integers without a decimal.

n does require float input, thus the cast.