Reputation: 53
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
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
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
Reputation: 301
Yes. See the Format Specification Mini-language:
>>> pi = 3.14159265
>>> print(f'{pi:.2f}')
3.14
Upvotes: 6