When should I use `int`, `float`, or `Decimal` for Python numbers?
Quick answer
Use int for whole-number values, float for fractional calculations where a binary approximation is acceptable, and Decimal when decimal representation or controlled rounding matters. Many decimal fractions cannot be represented exactly as float, so 0.1 + 0.2 may not equal exactly 0.3. For decimal input, construct Decimal from a string, such as Decimal('0.1'), rather than from a float.
The question, the details, the next step.
A practical checklist
Is the value a whole-number count? Choose
int.Is it a fractional calculation where a binary approximation is acceptable? Consider
float.Does decimal representation or controlled rounding matter? Consider
Decimal.When using
Decimal, construct written decimal inputs from strings, such asDecimal("0.1").If rounding matters, identify the required policy and check the
Decimalcontext rather than assuming a type choice decides it.
A few more useful answers
Why can `0.1 + 0.2` differ from `0.3` with floats?
Python floats use binary floating-point, and many decimal fractions are only approximations in that representation. Operations can introduce rounding error, so the result may not be exactly 0.3.[S2]
Should I use `Decimal` for every fractional number?
Not necessarily. Use float when approximate fractional arithmetic is acceptable; consider Decimal when decimal representation or controlled rounding matters.[S2]
Does using `Decimal` choose the rounding rule for me?
No. Decimal arithmetic uses a context that controls precision and rounding, but you still need to determine which policy fits your task.[S1]
Sources
References used for this guide.
- [S1] decimal — Decimal fixed point and floating point arithmetic docs.python.org · Checked
- [S2] Floating-Point Arithmetic: Issues and Limitations docs.python.org · Checked
