Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用科学记数法显示小数_Python_String Formatting_Number Formatting_Scientific Notation - Fatal编程技术网

Python 用科学记数法显示小数

Python 用科学记数法显示小数,python,string-formatting,number-formatting,scientific-notation,Python,String Formatting,Number Formatting,Scientific Notation,如何显示此项: 十进制('4080000000000.00000000000000')为'4.08E+10' 我试过这个: >>> '%E' % Decimal('40800000000.00000000000000') '4.080000E+10' 但它有额外的0 from decimal import Decimal '%.2E' % Decimal('40800000000.00000000000000') # returns '4.08E+10' 在您的“408

如何显示此项:

十进制('4080000000000.00000000000000')为'4.08E+10'

我试过这个:

>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
但它有额外的0

from decimal import Decimal

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'
在您的“4080000000000.00000000000000”中,有许多更重要的零与任何其他数字具有相同的含义。这就是为什么你必须明确说出你想停在哪里

如果要自动删除所有尾随零,可以尝试:

def format_e(n):
    a = '%E' % n
    return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]

format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'

format_e(Decimal('40000000000.00000000000000'))
# '4E+10'

format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'

请参见中的表格,以选择正确的格式布局。在你的例子中是
%.2E
我的小数太大了,不适合
%E
,所以我不得不临时修改:

def format_decimal(x, prec=2):
    tup = x.as_tuple()
    digits = list(tup.digits[:prec + 1])
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in digits[1:])
    exp = x.adjusted()
    return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)
下面是一个示例用法:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf

下面是一个使用
format()
函数的示例:

>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
除格式外,您还可以使用:


要将十进制转换为科学记数法,无需指定格式字符串中的精度,也不包括尾随的零,我目前正在使用

def sci_str(dec):
    return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)

print( sci_str( Decimal('123.456000') ) )    # 1.23456E+2

要保留任何尾随零,只需删除
normalize()

这对我最有效:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10
根据你的号码

x = Decimal('40800000000.00000000000000')
从Python 3开始

'{:.2e}'.format(x)
这是推荐的方法


e
表示需要科学记数法,
.2
表示需要点后两位数字。因此,您将获得
x.xxE±n
没有人提到
方法的缩写形式

至少需要Python 3.6

f"{Decimal('40800000000.00000000000000'):.2E}"

(我相信它和Cees Timmerman一样,只是短了一点)

我更喜欢Python 3.x方式

cal = 123.4567
print(f"result {cal:.4E}")
4
表示浮动部分中显示的位数

cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")

这是“简单”答案和评论的综合列表

PYTHON 3 或不带
导入
比较
这是我能找到的最简单的一个

format(40800000000.00000000000000, '.2E')
#'4.08E+10'

('E'不区分大小写。您也可以使用'.2e')

类似于双重发布,您可以使用刚刚开始的主题:不,一点也不。我想把它分为简单的问题(如何在Python中实现)和困难的、模糊的问题(如何在Django中实现),我怀疑任何人都不会回答这个问题。注意这已经有了答案。如果我把它们放在一起的话,我现在距离最终答案只有一半了,而不是0%。除此之外,将问题分开可以让人们更容易地寻找答案。例如,如果Bob正在搜索十进制格式问题,他可能会跳过标题中带有Django的SO questin。顺便说一句,尽管即使在Python 3标准库中仍在使用
format%values
语法,但我相信它在Python 3中在技术上不受欢迎,或者至少不是推荐的格式方法,当前推荐的语法,从Python2.6开始,应该是
'{0.2E}'。格式(十进制('4080000000000.00000000000000'))
(或者在Python2.7+中
'{.2E}'
。虽然在这种情况下没有严格意义上的用处,但由于没有添加功能的附加字符,
str.format
允许更复杂的格式参数混合/重新排列/重新使用。@CharlieParker Use。在win32上,format(n)
返回Python 3.3.2(v3.3.2:d047928ae3f6,2013年5月16日,00:06:53)中的
'3.39e+7800'
。使用十进制的目的是获得精确和任意精度的十进制算法。这并不等同于使用浮点数。@asmurer感谢您的澄清。更改了我的答案。有没有办法从这里返回到float?@olenscki只需执行
float(x)
即可将x转换为float。此语法也适用于3.6+
f“{Decimal('4080000000000.00000000000000'):.2E}”中的f字符串,应接受此答案。f-strings是python字符串格式的未来:)作为像我这样的未来读者的参考:如果您不想控制数字的数量,也不介意浮点错误,您可以简单地使用
{num:E}
,其中例如num=4080000000000.00000000000000有关格式示例用法的信息:
cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
from decimal import Decimal

x = '40800000000.00000000000000'
# Converted to Float
x = Decimal(x)

# ===================================== # `Dot Format`
print("{0:.2E}".format(x))
# ===================================== # `%` Format
print("%.2E" % x)
# ===================================== # `f` Format
print(f"{x:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{x:.2E}") == ("%.2E" % x) == ("{0:.2E}".format(x)))
# True
print(type(f"{x:.2E}") == type("%.2E" % x) == type("{0:.2E}".format(x)))
# True
# =====================================
# NO IMPORT NEEDED FOR BASIC FLOATS
y = '40800000000.00000000000000'
y = float(y)

# ===================================== # `Dot Format`
print("{0:.2E}".format(y))
# ===================================== # `%` Format
print("%.2E" % y)
# ===================================== # `f` Format
print(f"{y:.2E}")
# =====================================
# ALL Return: 4.08E+10
print((f"{y:.2E}") == ("%.2E" % y) == ("{0:.2E}".format(y)))
# True
print(type(f"{y:.2E}") == type("%.2E" % y) == type("{0:.2E}".format(y)))
# True
# =====================================
# =====================================
x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0

type(x)
# <class 'decimal.Decimal'>
type(y)
# <class 'float'>

x == y
# True
type(x) == type(y)
# False

x
# Decimal('40800000000.00000000000000')
y
# 40800000000.0
print("{0:.2E}".format(y))
format(40800000000.00000000000000, '.2E')
#'4.08E+10'