gpt4 book ai didi

Python 一般数字格式化行为

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:55 24 4
gpt4 key购买 nike

我使用通用格式选项将 float 打印为字符串,但我发现这种行为有些不寻常。例如,指定精度(小数点后的位数)时:对于 float 格式:

In [1]: '%f' % 123.456
Out[1]: '123.456000'

In [2]: '%.1f' % 123.456
Out[2]: '123.5'

按预期工作。现在,将其与以下内容进行比较:

In [3]: '%g' % 123.456
Out[3]: '123.456'

In [4]: '%.1g' % 123.456
Out[4]: '1e+02'

或者更糟:

In [6]: '%5g' % 123.456
Out[6]: '123.456'

In [7]: '%.5g' % 123.456
Out[7]: '123.46'

它似乎将“精度”值表示为“宽度”。这是一个错误,还是预期的行为?

诗。我想要的是用最少的所需字符打印 float (达到给定的精度)。例如:精度为 1 的 0.301238 打印为 0.3; 100.0003(精度为 1)打印为 100;

最佳答案

The formatting spec状态:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content. The precision is not allowed for integer values.

(已添加强调)

这是预期的行为。

我不相信有一种方法可以仅使用字符串格式来获取一位有效数字(您似乎想要的)。 Manually manipulating the number是必需的。

>>> from math import log10, floor
>>> def round_to_1(x):
... return round(x, -int(floor(log10(x))))
...
>>> "{:g}".format(round_to_1(0.301238))
0.3
>>> "{:g}".format(round_to_1(100.0003))
100

关于Python 一般数字格式化行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com