Python f字符串(PEP 498)有一种简单的方法可以修复小数点后的位数吗? (特别是f-strings,而不是其他字符串格式化选项,如.format或%)
例如,假设我想在小数位后面显示2位数。
我该怎么做?
a = 10.1234
f'{a:.2}'
Out[2]: '1e+01'
f'{a:.4}'
Out[3]: '10.12'
a = 100.1234
f'{a:.4}'
Out[5]: '100.1'
正如您所看到的,“精确度”已经改变了“小数点后的位数”的含义,就像使用%格式时的情况一样,仅改为总数。我怎么能始终在小数点后得到2位数,无论我有多大的数字?
答案 0 :(得分:196)
在格式表达式中包含类型说明符:
>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'
答案 1 :(得分:36)
对于float
号码,您可以使用format specifiers:
f'{value:{width}.{precision}}'
其中:
value
是任何计算结果为width
指定要显示的总计字符数,但如果value
需要的空间大于宽度指定的空间,则使用额外的空格。 precision
表示小数点后使用的字符数您缺少的是十进制值的类型说明符。在这个link中,您可以找到浮点和小数的可用表示类型。
这里有一些示例,使用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'
答案 2 :(得分:18)
罗伯(Robs)的回答:如果您要打印大量数字,使用千位分隔符可能会很有帮助(请注意逗号)。
>>> f'{a*1000:,.2f}'
'10,123.40'
答案 3 :(得分:15)
使用带有 f个字符串(more here)的格式说明符。
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$
答案 4 :(得分:2)
>>> 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
答案 5 :(得分:1)
四舍五入...
import datetime as dt
now = dt.datetime(2000, 1, 30, 15, 10, 15, 900)
now_mil = round(now.microsecond/1000)
print(f"{now:%Y/%m/%d %H:%M:%S.}{now_mil:03}")
输出:2000/01/30 15:10:15.001
答案 6 :(得分:0)
a = 10.1234
print(f"{a:0.2f}")
在0.2f中:
有关f字符串的数字的详细视频 https://youtu.be/RtKUsUTY6to?t=606
答案 7 :(得分:0)
简单
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
只需更改小数点符号后的值,该值代表您要打印的小数点数。