Junior
What is the difference between the data types decimal and float in Python?
sobes.tech AI
Answer from AI
float uses a binary floating-point representation, which can lead to inaccuracies when working with decimal fractions due to the nature of binary conversion. decimal stores decimal numbers exactly, without rounding, making it preferable for financial calculations and other tasks requiring high precision. decimal is slower and consumes more memory than float.
# Example with float
a = 0.1 + 0.1 + 0.1
print(f"{a=}") # a=0.30000000000000004
# Example with decimal
from decimal import Decimal
b = Decimal('0.1') + Decimal('0.1') + Decimal('0.1')
print(f"{b=}") # b=Decimal('0.3')
| Attribute | float |
decimal |
|---|---|---|
| Precision | Approximate (binary representation) | Exact (decimal representation) |
| Speed | Faster | Slower |
| Memory | Less | More |
| Use case | Scientific calculations where precision is not critical | Financial calculations, precise computations |