Python - High-precision calculations with Decimal


Python Clean Code Tip:

Avoid using floats when you need precise results. Use Decimal instead.

e.g. prices

👇

from dataclasses import dataclass


# bad
from decimal import Decimal


@dataclass
class Product:
    price: float


print(Product(price=0.1 + 0.2))
# => Product(price=0.30000000000000004)


# good
@dataclass
class Product:
    price: Decimal


print(Product(price=Decimal("0.1") + Decimal("0.2")))
# => Product(price=Decimal('0.3'))