Overview Precision is the backbone of financial software. Whether you are building a webshop backend or a quantitative trading platform, representing money accurately is a non-negotiable requirement. While many developers reach for floats due to their speed, the binary representation of floating-point numbers leads to rounding errors that are unacceptable in accounting. This guide explores how to use Decimal and integer-based patterns to maintain financial integrity in Python. Prerequisites To follow this tutorial, you should have a baseline understanding of Python data types. Familiarity with classes, specifically Python Data Classes, will help you understand the custom implementations for monetary objects. 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 CPUs have dedicated hardware for them, but they use a base-2 representation. This means simple calculations like `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. ```python 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, Decimal is significantly slower than other types and is a Python-specific object, which can lead to precision loss when serializing to databases that don't support the format natively. The Integer Pattern Top-tier payment providers like Stripe represent money as integers in the smallest currency unit (e.g., cents). This is fast, memory-efficient, and highly compatible with JSON and databases. ```python 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 numpy for single-value monetary tracking. Its fixed-size types (like `int64`) can overflow if you're dealing with massive sums in cents. Stick to Python's native `int`, which has arbitrary precision and will grow to fit your number as long as memory allows.
CPU
Hardware
May 2023 • 1 videos
High activity month for CPU. ArjanCodes among the most active voices, with 1 videos across 1 sources.
May 2023
- May 26, 2023