简体   繁体   English

使用 f-string 舍入浮点数

[英]Rounding float using f-string

Using %-formatting, I can round the number of decimal cases in a string:使用 %-formatting,我可以对字符串中的小数位数进行四舍五入:

pi = 3.14159265
print('pi = %0.2f' %pi)

And in output(in terminal) this would give me:在输出(在终端)中,这会给我:

pi = 3.14

Can I use f-strings do this task?我可以使用 f-strings 来完成这项任务吗? This feature has been added in Python 3.6此功能已添加到 Python 3.6

Include the type specifier in your format expression在格式表达式中包含类型说明符

format specifier:格式说明符:

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

example:例子:

# Formatted string literals
x = 3.14159265
print(f'pi = {x:.2f}')

Yes.是的。 See the Format Specification Mini-language :请参阅格式规范迷你语言

>>> pi = 3.14159265
>>> print(f'{pi:.2f}')
3.14

Of course you can do this.你当然可以这样做。 The code section would be代码部分将是

pi = 3.14159265
print(f"{pi:.2f}")

Output: 3.14 Output:3.14

if you want to print 3 decimal point then如果你想打印 3 个小数点然后

pi = 3.14159265
print(f"{pi:.3f}")

Output: 3.142 Output:3.142

You can also use.format method to do this job.您也可以使用 .format 方法来完成这项工作。 like this:像这样:

pi = 3.14159265
print("{:.2f}".format(pi))

Output: 3.14 Output:3.14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM