.2 和 .2f 格式说明符有什么区别?
What is the difference between .2 and .2f format specifiers?
考虑以下代码段:
for value in [1.123, 1.126, 1.12, 1.16, 1.1, 1.0, 12345.6789]:
print(
f'Testing {value:>12}',
f'.2 {value:>17.2}',
f'.2g {value:>16.2g}',
f'.2f {value:>16.2f}',
end='\n\n',
sep='\n'
)
代码显示{value:.2}
和{value:.2f}
输出不同的结果。
输出:
Testing 1.123
.2 1.1
.2g 1.1
.2f 1.12
Testing 1.126
.2 1.1
.2g 1.1
.2f 1.13
Testing 1.12
.2 1.1
.2g 1.1
.2f 1.12
Testing 1.16
.2 1.2
.2g 1.2
.2f 1.16
Testing 1.1
.2 1.1
.2g 1.1
.2f 1.10
Testing 1.0
.2 1.0
.2g 1
.2f 1.00
Testing 12345.6789
.2 1.2e+04
.2g 1.2e+04
.2f 12345.68
.2f
说明符将数字转换为定点表示法。
我发现 .2
和 .2g
相似但不完全相同。
.2
说明符的预期行为是什么?
Type: None
Meaning: For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.
我读到的意思是当没有给出后缀(例如 f
)时,样式 g
用于浮点数,除了像 1.0:.2
这样的情况将包括 .0
(“小数点后至少一位”),而 1.0:.2g
则不会。
g
的说明包括指定
... insignificant trailing zeros are removed.
考虑以下代码段:
for value in [1.123, 1.126, 1.12, 1.16, 1.1, 1.0, 12345.6789]:
print(
f'Testing {value:>12}',
f'.2 {value:>17.2}',
f'.2g {value:>16.2g}',
f'.2f {value:>16.2f}',
end='\n\n',
sep='\n'
)
代码显示{value:.2}
和{value:.2f}
输出不同的结果。
输出:
Testing 1.123
.2 1.1
.2g 1.1
.2f 1.12
Testing 1.126
.2 1.1
.2g 1.1
.2f 1.13
Testing 1.12
.2 1.1
.2g 1.1
.2f 1.12
Testing 1.16
.2 1.2
.2g 1.2
.2f 1.16
Testing 1.1
.2 1.1
.2g 1.1
.2f 1.10
Testing 1.0
.2 1.0
.2g 1
.2f 1.00
Testing 12345.6789
.2 1.2e+04
.2g 1.2e+04
.2f 12345.68
.2f
说明符将数字转换为定点表示法。
我发现 .2
和 .2g
相似但不完全相同。
.2
说明符的预期行为是什么?
Type: None
Meaning: For float this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.
我读到的意思是当没有给出后缀(例如 f
)时,样式 g
用于浮点数,除了像 1.0:.2
这样的情况将包括 .0
(“小数点后至少一位”),而 1.0:.2g
则不会。
g
的说明包括指定
... insignificant trailing zeros are removed.