print("%.2f" % total)

Frank Millman frank at chagford.com
Sun Nov 22 02:29:54 EST 2015


"Cai Gengyang"  wrote in message 
news:d34dc21b-fe74-40fc-9b54-c371105290f2 at googlegroups.com...


> meal = 44.50
> tax = 0.0675
> tip = 0.15
>
> meal = meal + meal * tax
> total = meal + meal * tip
>
> print("%.2f" % total)
>
> What do the lines inside the parentheses in this statement print("%.2f" % 
> total) mean ?
>
> What does "%.2f" % total represent ?

>From the Fine Manual -

Index > Symbols > '%' > Formatting takes you to a section headed 
"printf-style String Formatting".

"Given format % values (where format is a string), % conversion 
specifications in format are replaced with zero or more elements of values"

A conversion specifier consists of two or more characters, of which the 
first is always '%', and the rest provide a wide variety of formatting 
options.

Precision (optional) is given as a '.' (dot) followed by the precision, so 
'.2' means show the result with a precision of 2.

'f' is a conversion type which represents 'floating point decimal format'.

Note the following warning -

"The formatting operations described here exhibit a variety of quirks that 
lead to a number of common errors (such as failing to display tuples and 
dictionaries correctly). Using the newer str.format() interface helps avoid 
these errors, and also provides a generally more powerful, flexible and 
extensible approach to formatting text."

Using str.format(), your example would look like this -

print('{:.2f}'.format(total))

Another word of warning. Using a format specifier displays the value nicely 
rounded to a number of decimal places, but the original value is unchanged. 
Use the interpreter to see what the actual value is. For serious work 
involving monetary values, you should look at the Decimal module.

Frank Millman





More information about the Python-list mailing list