Please explain print("%.2f" % total)


I got the answer right but not with this code


The unit on Strings and Console Output introduces string formatting with the modulo operator. This is not a math operation, but symbolic for placeholder with data type specified.


This is the placeholder, which must be accompanied by a data type. Eg.

 > a = 4
 > print "%" % a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: incomplete format

Common type specifiers

s # string
r # representation (can be an expression or object)
d # decimal integer
b # binary integer
f # float

There are other presentation types listed in the documentation for Python 2.x.x.

To specify the number of decimal places to represent in a float, we use the dot integer modifier:

"%.4f"    # will include up to four decimal places, rounded using the 4/5 rule.

 > from math import pi
 > print "%.4f" % pi


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.