Python 浮点格式 - 类似“g”,但数字更多

问题描述 投票:0回答:4

我使用

"g"
来格式化浮点值,但它对我来说太快切换到科学格式化 - 在第 5 位数字处:

>>> format(0.0001, "g")
'0.0001'
>>> format(0.00001, "g")
'1e-05'

这似乎在

"g"
规则(-4)中进行了描述:

具体规则如下:假设用表示类型“e”和精度 p-1 格式化的结果将具有指数 exp。那么如果 -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.

有没有办法显示像

"g"
这样的数字,但在切换到科学计数法之前显示更多位数?

我正在考虑使用

".6f"
并去掉尾随零,但这样我就看不到需要科学记数法的小数字了。

python formatting floating-point
4个回答
10
投票

我也有同样的疑问。

查看 Python 文档,似乎 g 也支持精度值:

通用格式。对于给定精度 p >= 1,这将四舍五入 数字到 p 有效数字,然后将结果格式化为 定点格式或科学记数法,具体取决于其 幅度。

我不知道,为什么其他答案不使用这个,而且我在 Python 方面也不是很有经验,但它确实有效。

这可以通过使用

format(0.00001, '.10g')
来简单实现,其中 10 是您想要的精度。


4
投票
from math import log10

if log10(n) < -5:
    print "%e" % n
else:
    print "%f" % n

编辑:也可以将其放在一行上:

("%e" if log10(n) < -5 else "%f") % n

如果 n 可能为负数,则使用

log10(abs(n))
代替
log10(n)

编辑2:根据Adal的评论进行改进:

"%e" % n if n and log10(abs(n)) < -5 else ("%f" % n).rstrip("0")

这会将 0 打印为“0”。——如果您想要其他表示形式,例如“0”或“0.0”,则需要使用单独的

if
对其进行特殊处理。


3
投票

如果您使用的是 Python 2.7,您可以使用其高级字符串格式迷你语言

执行以下操作
>>> '{number:.{width}f}'.format(number=0.000000000001, width=20)
'0.00000000000100000000'

然后您可以动态指定所需的

number
width
值。


0
投票

尝试: 如果绝对值(log10(n))> = 5: 经过 #print("数字 N 是:","%e" % n) #别的: # print("数字 N 是:","%f" % n) 除了值错误: print("数字 N 是:","%e" % n) 别的: 如果绝对值(log10(E))> = 5: print("数字 N 是:","%e" % n) 别的: print("数字 N 是:","%f" % n)

© www.soinside.com 2019 - 2024. All rights reserved.