Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

Making it look right

It's nice to be able to include variables in template strings, but sometimes the variables need a bit of coercion to make them look the way we want them to in the output. For example, if we are performing calculations with currency, we may end up with a long decimal that we don't want to show up in our template:

subtotal = 12.32tax = subtotal * 0.07total = subtotal + taxprint(    "Sub: ${0} Tax: ${1} Total: ${total}".format(        subtotal, tax, total=total    ))

If we run this formatting code, the output doesn't quite look like proper currency:

Sub: $12.32 Tax: $0.8624 Total: $13.182400000000001
Technically, we should never use floating-point numbers in currency calculations like this; we should construct decimal.Decimal() objects ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content