Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 334
Heyl Avatar asked Dec 14 '22 10:12

Heyl


2 Answers

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}')
like image 191
ncica Avatar answered Dec 25 '22 11:12

ncica


Yes. See the Format Specification Mini-language:

>>> pi = 3.14159265
>>> print(f'{pi:.2f}')
3.14
like image 42
RGMyr Avatar answered Dec 25 '22 11:12

RGMyr