A float is a fundamental data type in Python used to represent real numbers, which are numbers that have a fractional part. This includes positive and negative numbers with decimals.
You would use this data type for any value that isn't a whole number, such as a person's height, the price of an item, a scientific measurement, or the result of a division that has a remainder.
Precision and Representation
It's important to know that floats are stored in a computer's memory using a format called binary floating-point. This means that most decimal fractions cannot be stored with perfect precision. This can sometimes lead to small, surprising rounding errors in calculations. For most applications, this isn't a problem, but it's something to be aware of, especially in high-precision financial or scientific calculations.
Operations Possible on Floats
Floats support the same arithmetic and comparison operations as integers.
- Arithmetic Operations: You can perform addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulus (%), and exponentiation (**) with floats. The result of these operations is almost always another float.
- Comparison Operations: You can compare floats using ==, !=, <, >, <=, and >=. These operations return a boolean (True or False).
Built-in Functions for Floats
Several built-in Python functions are very useful for working with floats.
- round(number, ndigits): Rounds a float to a specified number of decimal places.
- abs(): Returns the absolute (non-negative) value.
- int(): Converts a float to an integer by truncating (cutting off) the decimal part.
- float(): Can be used to convert other data types, like integers or strings, into a float.
Float Methods
Float objects have a few specific methods for more advanced use cases.
- .is_integer(): Returns True if the float represents a whole number (e.g., 5.0), and False otherwise (e.g., 5.1).
- .as_integer_ratio(): Returns a pair of integers (a tuple) whose ratio is exactly equal to the float. This can be useful for working with fractions.
# --- 1. Arithmetic Operations ---
# These are the standard mathematical operations. Floats are used for decimal precision.
a = 10.5
b = 3.0
print("--- Arithmetic Operations ---")
print(f"Addition (a + b): {a + b}")
print(f"Subtraction (a - b): {a - b}")
print(f"Multiplication (a * b): {a * b}")
print(f"Standard Division (a / b): {a / b}")
print(f"Floor Division (a // b): {a // b}") # Note: Still results in a float (e.g., 3.0)
print(f"Modulus (a % b): {a % b}") # Gives the remainder
print(f"Exponentiation (a ** b): {a ** b}")
# --- 2. Comparison Operations ---
# These operations compare two floats and return True or False.
print("\n--- Comparison Operations ---")
print(f"Is 5.0 equal to 5? (5.0 == 5): {5.0 == 5}") # Note: A float can equal an int
print(f"Is a not equal to b? (a != b): {a != b}")
print(f"Is a greater than b? (a > b): {a > b}")
print(f"Is a less than or equal to b? (a <= b): {a <= b}")
# --- 3. Built-in Functions ---
# Python provides several useful functions that work with floats.
pi = 3.14159265
negative_float = -99.9
print("\n--- Built-in Functions ---")
print(f"Rounding pi to 2 decimal places: {round(pi, 2)}")
print(f"Absolute value of {negative_float}: {abs(negative_float)}")
print(f"Converting pi to an integer (truncates): {int(pi)}")
print(f"Converting the integer 10 to a float: {float(10)}")
# --- 4. Float Methods ---
# Floats have a few specific methods for more advanced tasks.
num1 = 5.0
num2 = 5.25
print("\n--- Float Methods ---")
# .is_integer() checks if the float has no fractional part.
print(f"Is {num1} an integer? {num1.is_integer()}")
print(f"Is {num2} an integer? {num2.is_integer()}")
# .as_integer_ratio() expresses the float as a fraction.
# For 5.25, this is 21/4.
numerator, denominator = num2.as_integer_ratio()
print(f"The float {num2} can be represented as the fraction: {numerator} / {denominator}")
# --- 5. Precision Issues ---
# A quick example of the floating-point precision issue.
# In binary, 0.1 + 0.2 is not exactly 0.3.
val1 = 0.1
val2 = 0.2
result = val1 + val2
print("\n--- Floating-Point Precision Example ---")
print(f"0.1 + 0.2 = {result}")
print(f"Is the result exactly 0.3? {result == 0.3}")
# This is why for critical comparisons, it's often better to check if numbers are "close enough".
print(f"Is the result close to 0.3? {abs(result - 0.3) < 0.000001}")