简体   繁体   English

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

[英]How to suppress scientific notation when printing float values?

Here's my code:这是我的代码:

x = 1.0
y = 100000.0    
print x/y

My quotient displays as 1.00000e-05 .我的商显示为1.00000e-05

Is there any way to suppress scientific notation and make it display as 0.00001 ?有什么办法可以抑制科学记数法并使其显示为0.00001吗? I'm going to use the result as a string.我将使用结果作为字符串。

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).使用较新版本''.format (还记得在.之后指定要显示的位数,这取决于浮点数有多小)。 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:如上所示,默认为 6 位,这对我们的案例示例没有帮助:因此我们可以使用如下内容:

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

Update更新

Starting in Python 3.6, this can be simplified with the new formatted string literal , as follows:从 Python 3.6 开始,可以使用新 的格式化字符串字面量进行简化,如下所示:

>>> f'{a:.20f}'
'-0.00000000000000007186'
'%f' % (x/y)

but you need to manage precision yourself.但是您需要自己管理精度。 eg,例如,

'%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或者对于 Python 3 等效的旧格式更新样式的格式

With newer versions of Python (2.6 and later), you can use''.format() to accomplish what @SilentGhost suggested:使用较新版本的 Python(2.6 及更高版本),您可以使用''.format()来完成@SilentGhost 建议的操作:

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

Another option, if you are using pandas and would like to suppress scientific notation for all floats, is to adjust the pandas options.如果您使用 pandas 并且想禁止所有浮点数的科学记数法,另一个选项是调整 pandas 选项。

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

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 numpy有一个答案: np.format_float_positional

import numpy as np

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

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

This is using Captain Cucumber's answer , but with 2 additions.这是使用黄瓜船长的答案,但增加了 2 个。

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. 1) 允许 function 获取非科学计数法数字并按原样返回它们(因此您可以输入大量输入,其中一些数字是 0.00003123 与 3.123e-05 并且仍然有 function 工作。

2) added support for negative numbers. 2) 增加了对负数的支持。 (in original function, a negative number would end up like 0.0000-108904 from -1.08904e-05) (在原始 function 中,负数最终会像 -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

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如果它是一个string ,则使用内置的float进行转换,例如: print( "%.5f" % float("1.43572e-03")) answer: 0.00143572

Since this is the top result on Google, I will post here after failing to find a solution for my problem.由于这是 Google 上的最高结果,因此在未能找到解决问题的方法后,我将在此处发布。 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:如果您希望格式化浮点 object 的显示值并使其保持浮点而不是字符串,则可以使用此解决方案:

Create a new class that modifies the way that float values are displayed.创建一个新的 class 来修改浮点值的显示方式。

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}您可以通过更改{:f}中的 integer 值自己修改精度

In addition to SG's answer, you can also use the Decimal module:除了 SG 的回答,您还可以使用 Decimal 模块:

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

# x is a string '0.0001'

A simpler solution to display a float to an arbitrary number of significant digits.将浮点数显示为任意数量的有效数字的更简单的解决方案。 No numpy or list comprehensions required here:此处不需要numpy或列表推导:

def sig(num, digits=3):
    "Return number formatted for significant digits"
    if num == 0:
        return 0
    negative = '-' if num < 0 else ''
    num = abs(float(num))
    power = math.log(num, 10)
    if num < 1:
        step = int(10**(-int(power) + digits) * num)
        return negative + '0.' + '0' * -int(power) + str(int(step)).rstrip('0')
    elif power < digits - 1:
        return negative + ('{0:.' + str(digits) + 'g}').format(num)
    else:
        return negative + str(int(num))

I'm stripping trailing 0s and displaying full integers in the example: sig(31415.9) = 31415 instead of 31400. Feel free to modify the code if that's not something you're into.我在示例中去除尾随 0 并显示完整整数: sig(31415.9) = 31415而不是 31400。如果您不喜欢,请随意修改代码。

Testing:测试:

for power in range(-8,8):
    num = math.pi * 10**power
    print(str(num).ljust(25), sig(num))

You can use the built-in format function.您可以使用内置format function。

>>> a = -3.42142141234123e-15
>>> format(a, 'f')
'-0.000000'
>>> format(a, '.50f') # Or you can specify precision
'-0.00000000000000342142141234122994048466990874926279'

In case of numpy arrays you can suppress with suppress command as在 numpy arrays 的情况下,您可以使用抑制命令进行抑制

import numpy as np np.set_printoptions(suppress=True)导入 numpy 作为 np np.set_printoptions(suppress=True)

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:使用 3.6.4 时,我遇到了一个类似的问题,即在使用这个时,output 文件中的一个数字将被格式化为科学计数法:

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':我所要做的就是添加'f':

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

As of 3.6 (probably works with slightly older 3.x as well), this is my solution:从 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')

The purpose of the precision calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6). precision计算的目的是确保我们有足够的精度来避免科学记数法(默认精度仍然是 6)。

The dec_precision argument adds additional precision to use for decimal points. dec_precision参数增加了用于小数点的额外精度。 Since this makes use of the n format, no insignificant zeros will be added (unlike f formats).由于这使用了n格式,因此不会添加无关紧要的零(与f格式不同)。 n also will take care of rendering already-round integers without a decimal. n也将负责呈现没有小数的已舍入整数。

n does require float input, thus the cast. n确实需要float输入,因此需要强制转换。

I was having a similar problem that randomly, using my solution:我随机遇到了类似的问题,使用我的解决方案:

from decimal import Decimal

Decimal(2/25500)
#output:0.00007843137254901961000728982664753630160703323781490325927734375

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM