Decimal vs float in Python


Python tip:

You can use Decimal instead of float to:

  1. incorporate a notion of significant places (1.20 + 1.30 = 2.50)
  2. represent decimal numbers exactly (1.1 + 2.2 = 3.3)

In short, use Decimal when precision matters.

An example 👇

from decimal import Decimal

print(1.20 + 1.30)
# => 2.5

print(Decimal("1.20") + Decimal("1.30"))
# => 2.50

print(1.1 + 2.2)
# => 3.3000000000000003

print(Decimal("1.1") + Decimal("2.2"))
# => 3.3