Heyl
Heyl

Reputation: 53

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

Upvotes: 5

Views: 7389

Answers (3)

Abu Bakar Siddik
Abu Bakar Siddik

Reputation: 459

Of course you can do this. The code section would be

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

Output: 3.14

if you want to print 3 decimal point then

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

Output: 3.142

You can also use .format method to do this job. like this:

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

Output: 3.14

Upvotes: 1

ncica
ncica

Reputation: 7206

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

Upvotes: 6

RGMyr
RGMyr

Reputation: 301

Yes. See the Format Specification Mini-language:

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

Upvotes: 6

Related Questions