Financial Integrity in Python: Beyond the Floating Point
Overview
Precision is the backbone of financial software. Whether you are building a webshop backend or a quantitative trading platform, representing
Prerequisites
To follow this tutorial, you should have a baseline understanding of
Key Libraries & Tools
- decimal: A built-in module for fixed and floating-point arithmetic with user-defined precision.
- timeit: A tool used to measure the execution time of small code snippets.
- numpy: A library for numerical computing, used here to demonstrate the limitations of fixed-size data types.
The Danger of Floats
Floats are fast because 1.1 + 2.2 result in 3.3000000000000003. In finance, these tiny fractions accumulate into massive discrepancies.
Precise Arithmetic with Decimals
The decimal module provides a Decimal type that uses base-10 internally, mimicking how humans count money. You can control the rounding behavior and precision globally.
from decimal import Decimal, getcontext
# Set precision to two decimal places
getcontext().prec = 2
result = Decimal("1.1") + Decimal("2.2")
print(result) # Output: 3.3
While precise,
The Integer Pattern
Top-tier payment providers like
from dataclasses import dataclass
@dataclass
class Money:
amount_in_cents: int
currency: str = "$"
def __str__(self):
return f"{self.currency}{self.amount_in_cents / 100:.2f}"
# $10.50 is stored as 1050
wallet = Money(1050)
print(wallet) # Output: $10.50
Syntax Notes
Using dunder methods (like __add__ or __str__) allows your custom Money class to behave like a native number. This makes your code more readable while keeping the underlying integer logic hidden.
Tips & Gotchas
Avoid int64) can overflow if you're dealing with massive sums in cents. Stick to int, which has arbitrary precision and will grow to fit your number as long as memory allows.

Fancy watching it?
Watch the full video and context