以科学记数法显示小数

发布于 2024-11-27 09:46:48 字数 224 浏览 0 评论 0原文

如何将 Decimal('40800000000.00000000000000') 显示为 '4.08E+10'

我已经尝试过这个:

>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'

但它有那些额外的 0。

How can I display Decimal('40800000000.00000000000000') as '4.08E+10'?

I've tried this:

>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'

But it has those extra 0's.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

橘亓 2024-12-04 09:46:48
from decimal import Decimal

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

# returns '4.08E+10'

在“40800000000.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'
from decimal import Decimal

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

# returns '4.08E+10'

In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.

If you want to remove all trailing zeros automatically, you can try:

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'
指尖凝香 2024-12-04 09:46:48

以下是使用 format() 函数的示例:

>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'

除了格式之外,您还可以使用 f-strings:

>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'

Here's an example using the format() function:

>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'

Instead of format, you can also use f-strings:

>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
你的笑 2024-12-04 09:46:48

鉴于您的号码

x = Decimal('40800000000.00000000000000')

,从 Python 3 开始,

'{:.2e}'.format(x)

是推荐的方法。

e 表示您需要科学记数法,.2 表示您需要点后 2 位数字。所以你会得到x.xxE±n

Given your number

x = Decimal('40800000000.00000000000000')

Starting from Python 3,

'{:.2e}'.format(x)

is the recommended way to do it.

e means you want scientific notation, and .2 means you want 2 digits after the dot. So you will get x.xxE±n

哭泣的笑容 2024-12-04 09:46:48

没有人提到 .format 方法的简短形式:

至少需要 Python 3.6

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

(我相信它与 Cees Timmerman 相同,只是更短一点)

No one mentioned the short form of the .format method:

Needs at least Python 3.6

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

(I believe it's the same as Cees Timmerman, just a bit shorter)

眼眸里的那抹悲凉 2024-12-04 09:46:48

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

PYTHON 3

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
# =====================================

或没有 IMPORT

# 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

对于 Python 3,您现在可以在这三个中的任何一个之间切换。

我的最爱:

print("{0:.2E}".format(y))

This is a consolidated list of the "Simple" Answers & Comments.

PYTHON 3

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
# =====================================

OR Without IMPORT's

# 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
# =====================================

Comparing

# =====================================
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

So for Python 3, you can switch between any of the three for now.

My Fav:

print("{0:.2E}".format(y))
白鸥掠海 2024-12-04 09:46:48

请参阅 Python 字符串格式 中的表格来选择正确的格式布局。在您的情况下,它是 %.2E

See tables from Python string formatting to select the proper format layout. In your case it's %.2E.

愛上了 2024-12-04 09:46:48

这对我来说效果最好:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10

This worked best for me:

import decimal
'%.2E' % decimal.Decimal('40800000000.00000000000000')
# 4.08E+10
深海蓝天 2024-12-04 09:46:48

我更喜欢 Python 3.x 方式。

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

4表示浮动部分显示多少位。

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

I prefer Python 3.x way.

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

4 indicates how many digits are shown shown in the floating part.

cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")
一城柳絮吹成雪 2024-12-04 09:46:48

我的小数对于 %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

My decimals are too big for %E so I had to improvize:

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)

Here's an example usage:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf
﹉夏雨初晴づ 2024-12-04 09:46:48

要将小数转换为科学记数法,而不需要在格式字符串中指定精度,并且不包含尾随零,我当前使用的

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

To convert a Decimal to scientific notation without needing to specify the precision in the format string, and without including trailing zeros, I'm currently using

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

To keep any trailing zeros, just remove the normalize().

沫尐诺 2024-12-04 09:46:48

添加更新的答案以展示如何仅将e notation应用于小数字

value = 0.1
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 0.1

value = 0.00002488
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 2.488e-05

Adding an updated answer to show how to apply e notation to small numbers only

value = 0.1
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 0.1

value = 0.00002488
a = "{:,}".format(value) if value >= 0.001 else "{:,.3e}".format(value)
print(a) # 2.488e-05
所谓喜欢 2024-12-04 09:46:48

这是我能找到的最简单的一个。

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

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

Here is the simplest one I could find.

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

('E' is not case sensitive. You can also use '.2e')

我是有多爱你 2024-12-04 09:46:48
def formatE_decimal(x, prec=2):
    """ Examples:
    >>> formatE_decimal('0.1613965',10)
    '1.6139650000E-01'
    >>> formatE_decimal('0.1613965',5)
    '1.61397E-01'
    >>> formatE_decimal('0.9995',2)
    '1.00E+00'
    """
    xx=decimal.Decimal(x) if type(x)==type("") else x 
    tup = xx.as_tuple()
    xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
    tup = xx.as_tuple()
    exp = xx.adjusted()
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in tup[1][1:prec+1])   
    if prec>0:
        return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
    elif prec==0:
        return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
    else:
        return None
def formatE_decimal(x, prec=2):
    """ Examples:
    >>> formatE_decimal('0.1613965',10)
    '1.6139650000E-01'
    >>> formatE_decimal('0.1613965',5)
    '1.61397E-01'
    >>> formatE_decimal('0.9995',2)
    '1.00E+00'
    """
    xx=decimal.Decimal(x) if type(x)==type("") else x 
    tup = xx.as_tuple()
    xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
    tup = xx.as_tuple()
    exp = xx.adjusted()
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in tup[1][1:prec+1])   
    if prec>0:
        return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
    elif prec==0:
        return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
    else:
        return None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文