137

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

x = 3.14159265
print('pi = %0.2f' %x)

This would give me:

pi = 3.14

Is there any way of doing this using f-strings in Python 3.6?

elsoja
  • 1,567
  • 2
  • 9
  • 7
  • 1
    To be clear, you're only asking about round-to-nearest (like `%f` does), not round-down/truncate (like `int()`), round-up, round-towards-zero, round-towards-infinity or any other scheme? If only round-to-nearest, then this is a duplicate (cc: @vaultah) – smci Oct 20 '20 at 23:25
  • But either way, this title *"Rounding floats with f-string"* and tagging [tag:python-3.6] is much better, clearer, wording, legible and better search keyword coverage or duplicate than *"Convert floating point number to a certain precision, and then copy to string"*. So we should definitely leave this stand, closed but not deleted (cc: @vaultah) – smci Oct 20 '20 at 23:27

1 Answers1

293

How about this

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

Docs for f-strings

Joe Germuska
  • 1,638
  • 1
  • 18
  • 34
JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • 6
    Is the `.2f` required? It seems to work with just `.2`. – 101 Dec 12 '18 at 01:30
  • 29
    @101 Yes, it is necessary. Using `.2` will not give you the expected value! It will round down to total of 2 digit using scientific notation and will only work on float numbers instead of ints as well – JBernardo Dec 12 '18 at 12:48