Python f-string有没有一种简单的方法来固定小数点后的位数?(特别是f-string,而不是.format或%等其他字符串格式选项)

例如,假设我想在小数点后显示2位数字。

我该怎么做?让我们这么说吧

a = 10.1234

当前回答

a = 10.1234

print(f"{a:0.2f}")

在0.2f中:

0告诉python不限制陈列.2表示我们只想在小数后取2位(结果将与round()函数相同)f表示它是一个浮点数。如果你忘记了f,那么它只会在小数点后少打印1个数字。在这种情况下,它只能是小数后1位。

关于数字f-string的详细视频https://youtu.be/RtKUsUTY6to?t=606

其他回答

在格式表达式中包含类型说明符:

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

添加到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$
a = 10.1234

print(f"{a:0.2f}")

在0.2f中:

0告诉python不限制陈列.2表示我们只想在小数后取2位(结果将与round()函数相同)f表示它是一个浮点数。如果你忘记了f,那么它只会在小数点后少打印1个数字。在这种情况下,它只能是小数后1位。

关于数字f-string的详细视频https://youtu.be/RtKUsUTY6to?t=606

当涉及浮点数时,可以使用格式说明符:

f'{value:{width}.{precision}}'

哪里:

value是计算结果为数字的任何表达式width指定要显示的字符总数,但如果value需要的空间大于width指定的空间,则使用额外的空间。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'

仅仅

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

只需更改小数点符号后的值,小数点符号表示您要打印的小数点。