5

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

Granny Aching
  • 1,295
  • 12
  • 37
Heyl
  • 53
  • 1
  • 4
  • Does this answer your question? [Fixed digits after decimal with f-strings](https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings) – Florian Brucker Jan 24 '22 at 09:35

3 Answers3

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}')
ncica
  • 7,015
  • 1
  • 15
  • 37
6

Yes. See the Format Specification Mini-language:

>>> pi = 3.14159265
>>> print(f'{pi:.2f}')
3.14
RGMyr
  • 191
  • 5
1

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