首页 > 解决方案 > Rounding float using f-string

问题描述

Using %-formatting, I can round the number of decimal cases in a string:

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? This feature has been added in Python 3.6

标签: pythonstringmultilinef-string

解决方案


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}')

推荐阅读