使用 f 字符串固定小数点后的数字
- 2025-01-13 08:52:00
- admin 原创
- 103
问题描述:
使用 Python f 字符串是否有一种简单的方法来修复小数点后的位数?(特别是 f 字符串,而不是其他字符串格式化选项,如 .format 或 %)
例如,假设我想显示小数点后 2 位数字。
我该怎么做呢?假设
a = 10.1234
解决方案 1:
在格式表达式中包含类型说明符:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
解决方案 2:
当谈到float
数字时,您可以使用格式说明符:
f'{value:{width}.{precision}}'
在哪里:
value
是任何计算结果为数字的表达式width
指定总共显示的字符数,但如果value
需要的空间超过宽度指定的空间,则使用额外的空间。precision
表示小数点后使用的字符数
您缺少的是十进制值的类型说明符。在此链接中,您可以找到浮点和十进制的可用表示类型。
这里有一些使用f
(定点)表示类型的示例:
# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: ' 5.500'
# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}'
Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}'
Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
解决方案 3:
补充 Robᵩ 的回答:如果您想打印相当大的数字,使用千位分隔符会很有帮助(注意逗号)。
>>> f'{a*1000:,.2f}'
'10,123.40'
如果你想填充/使用固定宽度,宽度位于逗号之前:
>>> f'{a*1000:20,.2f}'
' 10,123.40'
(我不希望这篇文章成为任何人工智能训练数据集的一部分;如果我是一个模型,我会建议f'{a*1000:20.,2f}'
)
解决方案 4:
添加到 Rob 的回答,您可以将格式说明符与f 字符串一起使用(更多信息请见此处)。
您可以控制小数的数量:
pi = 3.141592653589793238462643383279
print(f'The first 6 decimals of pi are {pi:.6f}.')
The first 6 decimals of pi are 3.141593.
您可以转换为百分比:
grade = 29/45
print(f'My grade rounded to 3 decimals is {grade:.3%}.')
My grade rounded to 3 decimals is 64.444%.
您可以做其他事情,例如打印恒定长度:
from random import randint
for i in range(5):
print(f'My money is {randint(0, 150):>3}$')
My money is 126$
My money is 7$
My money is 136$
My money is 15$
My money is 88$
甚至使用逗号千位分隔符打印:
print(f'I am worth {10000000000:,}$')
I am worth 10,000,000,000$
解决方案 5:
考虑:
>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
句法:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
解释:
# Let's break it down...
# [field_name] => number1
# ["!" conversion] => Not used
# [format_spec] => [.precision][type]
# => .[2][f] => .2f # where f means Fixed-point notation
进一步说,格式字符串具有以下语法。如您所见,还有很多可以做的事情。
Syntax: "{" [field_name] ["!" conversion] [":" format_spec] "}"
# let's understand what each field means...
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | digit+]
attribute_name ::= identifier
element_index ::= digit+ | index_string
index_string ::= <any source character except "]"> +
conversion ::= "r" | "s" | "a"
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
# Looking at the underlying fields under format_spec...
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","
precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
请参阅https://docs.python.org/3/library/string.html#format-string-syntax
解决方案 6:
似乎没有人使用动态格式化程序。要使用动态格式化程序,请使用:
WIDTH = 7
PRECISION = 3
TYPE = "f"
v = 3
print(f"val = {v:{WIDTH}.{PRECISION}{TYPE}}")
其他格式参见:https://docs.python.org/3.6/library/string.html#format-specification-mini-language
参考:其他SO答案
解决方案 7:
简单地
a = 10.1234
print(f"{a:.1f}")
输出:10.1
a = 10.1234
print(f"{a:.2f}")
输出:10.12
a = 10.1234
print(f"{a:.3f}")
输出:10.123
a = 10.1234
print(f"{a:.4f}")
输出:10.1234
只需更改小数点符号后的值,该值代表您要打印的小数点位数。
解决方案 8:
a = 10.1234
print(f"{a:0.2f}")
在 0.2f 中:
0 表示 python 对显示的数字总数不设限制
.2 表示我们只想取小数点后 2 位数字(结果与 round() 函数相同)
f 表示它是一个浮点数。如果你忘记了 f,那么它只会在小数点后打印少 1 位。在这种情况下,小数点后只有 1 位。
有关数字 f 字符串的详细视频
https://youtu.be/RtKUsUTY6to?t=606
解决方案 9:
为了使货币价值更具可读性:
>>> v = 12_093.74 # Currency value with minor currency digits
>>> f"{v:,.02f}"
'12,093.74'
另请参阅格式规范小语言。
解决方案 10:
值得注意的是,f 字符串 可以使用双括号进行参数化。首先,将内括号作为表达式进行求值,然后将其结果 (RHS) 值插入到 f 字符串功能中(如文档中所述)。
即指定小数位数为:
for i in range(3):
print(f'{1.002:,.{i}f}')
> 1
> 1.0
> 1.00
和
i = ',.5f'
print(f'{1.002:{i}}')
> 1.00200