# Ints and Floats in Python: Avoid 2 Costly Mistakes

Numbers are the backbone of many Python programs. Understanding how Python handles different types of numbers, specifically ints (integers) and floats (floating-point numbers), is crucial for writing accurate and efficient code. Let’s delve into the intricacies of these numeric types.

### Understanding Ints and Floats

In Python:

• Ints: Represent whole numbers (positive, negative, or zero) without decimal points. Examples: `5`, `-10`, `0`.
• Floats: Represent real numbers with decimal points. Examples: `3.14`, `-0.5`, `100.0`.
``````x = 5       # int
y = 3.14   # float
``````

### Ints and Floats Interacting

When you perform arithmetic operations with ints and floats, Python usually returns a float:

``````result = 20 / 4    # result is 5.0 (float)
result = 2 + 3.14  # result is 5.14 (float)
``````

Casting: You can convert between types using `int()` and `float()`:

``````float_num = 8.999
int_num = int(float_num)  # int_num is 8 (truncates decimal)
``````

Important Note: Casting from float to int truncates the decimal portion; it does not round.

``````rounded_num = round(8.999)   # rounded_num is 9 (rounded to nearest integer)
``````

### Pitfalls to Avoid

1. Rounding Errors with Floats

Floats are approximations of real numbers due to the limitations of binary representation in computers. This can lead to unexpected results:

``````result = 1.2 - 1.0
print(result)  # Output: 0.19999999999999996
``````

Solution: Use the `round()` function when precision is important.

2. Losing Precision with Int Casting

Casting from float to int truncates the decimal portion, which can be problematic if you need those decimal values:

``````cost = 4.99
int_cost = int(cost)  # int_cost is 4
``````

Solution: Consider using the `decimal` module for financial calculations where rounding errors can be significant.

### When to Use Ints vs. Floats

• Ints: For counting discrete quantities, representing indices, or working with whole numbers.
• Floats: For measurements, calculations involving fractions, or when decimal precision is necessary.

1. Why are floats considered approximations in Python?

Floats are represented in binary format (0s and 1s) in computers. Some decimal numbers cannot be precisely represented in binary, leading to small rounding errors.

2. Is there a way to perform rounding instead of truncation when converting from float to int?

Yes, the `round()` function rounds floats to the nearest integer or a specified number of decimal places.

3. When should I use the `decimal` module instead of floats?

Use the `decimal` module for financial or other calculations where rounding errors can be critical. It provides decimal arithmetic with user-definable precision.

4. What are some other numeric types in Python?

Python also offers complex numbers (`complex`) for mathematical operations involving imaginary numbers.