2

How do I format a number to have a thousands separator and round to two decimals while trying to format a variable in? For example

print('{} earns {} a year".format(name, earnings ':,.2f')

doesn't seem to work. How do I add in both variables but format my number value?

  • Has an answer [here](https://stackoverflow.com/a/32777579/5223223). – dibery Mar 01 '21 at 03:00
  • While reading carefully the documentation (or that answer) would resolve the question, this error/mistake/misconception is oddly specific that it's virtually impossible to come up in a [search engine)] search. – user202729 Mar 01 '21 at 03:16

1 Answers1

1

You can enter the format inside the curly brackets.

Full example here: https://thepythonguru.com/python-string-formatting/

"Floating point {0:.2f}".format(345.7916732)

Expected output:

>>> Floating point 345.79

Likewise "Floating point pi = {0:.3f}, with {1:d} digit precision".format(math.pi, 3)

Expected output:

>>> Floating point pi = 3.142, with 3 digit precision

stephen
  • 71
  • 2