且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 f 字符串固定小数点后的数字

更新时间:2023-02-21 16:26:43

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

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

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %)

For example, let's say I want to display 2 digits after the decimal place.

How do I do that? Let's say that

a = 10.1234

Include the type specifier in your format expression:

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