2

I'm teaching myself some Python for a job opportunity. I've just started, and I can't seem to reconcile how one uses print"".format() to output floats with only two digits after the decimal.

I've tried putting .2f in different places; no luck.

This is what I have:

def displayEmployeeData(self):
    print "Name: {:<10} ID: {:<10} Team: {:<10} salary: ${:<10} tenure: {:<10} months".format(self.name, self.ID, self.team, self.salary, self.tenure)

3 Answers3

4

it follows the format

print '{arg_num: format} string".format(<tuple of args>)

So in your case, it would be like:

def displayEmployeeData(self):
    print "Name: {0} ID: {1} Team: {2} salary: ${3:.2f} tenure: {4} months".format(self.name, self.ID, self.team, self.salary, self.tenure)
Vj-
  • 722
  • 6
  • 18
1

You need to use {0:.xf} where 0 is the argument number and x is the number of digits you want.

>>> print "{0:.3f} something".format(2.234234239)
>>> 2.234 something

Please go through the documentation for more formatting details.

Jay
  • 2,431
  • 1
  • 10
  • 21
1

You have these two ways:

print("{0:.3f} something".format(2.234234239))
print("{0:<10.3f} something".format(2.234234239))

or, alternatively:

data = 2.234234239
print(f"{data:.3f} something")
print(f"{data:<10.3f} something")

outputs:

2.234 something
2.234      something
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80