Back to course

The Floating Point Data Type (float)

Python Programming: The 0 to Hero Bootcamp

Floating Point Numbers (float)

Floats are numbers that contain a decimal point. They are used to represent non-integer values (e.g., 3.14, -0.001, 5.0).

python pi = 3.14159 price = 19.99 half = 0.5

Float Arithmetic

Floats can be used with all the same arithmetic operators as integers. The result of any operation involving at least one float will be a float.

python calc1 = 10 + 5.5 # Result is 15.5 (float) calc2 = 15.0 / 3 # Result is 5.0 (float) calc3 = 7.5 * 2.0 # Result is 15.0 (float)

Pitfalls of Floating Point Precision

Due to how computers store floating-point numbers in binary, sometimes small precision errors can occur. This is not specific to Python, but universal in computing.

python

This often results in a number slightly off 0.3

print(0.1 + 0.1 + 0.1)

Output: 0.30000000000000004

For financial calculations where precision is critical, we use the 'decimal' module, which we will cover later.