Recipes: Numbers and maths¶
Task-focused how-tos. If you know what you want to do but aren't sure how to build it, this is the section to skim.
Recipes in this section¶
- Round numbers correctly — why
round(2.5)is2, how to get the "round half up" most people expect, rounding to a number of decimal places or significant figures, and rounding money exactly. - Handle money with Decimal — the end-to-end pattern for currency: build
Decimals from strings, do exact arithmetic,quantizeto two places with a chosen rounding rule, and never let afloatnear it. - Format numbers for display — thousands separators, fixed decimal places, percentages, scientific notation, padding and alignment, signs, and other number formats with f-strings.
- Avoid common number mistakes — a catalogue of the traps: float equality,
Decimal(0.1)versusDecimal('0.1'), mixingDecimalandfloat,nancomparisons, lossysum, and more.