When performing numerical calculations in Python, type conversion (casting) between integers (int) and floating-point numbers (float) is a frequently used operation.
For example, you might want to convert an integer to a decimal for calculation, or remove the decimal part from a calculation result to get an integer.
This article explains how to convert between these types using the float() and int() functions, focusing on the “truncation” behavior when converting from float to int.
1. Converting Integers to Floats: float()
To convert an integer (int) to a floating-point number (float), use the built-in function float(). When converted, .0 is added to the end of the integer.
Syntax:
Python
float_number = float(integer)
Specific Usage Example:
Here is an example of converting a game score (integer) into a decimal format for calculations like averaging.
Python
# Integer score
current_score = 150
# Convert to float type
score_float = float(current_score)
print(f"Before: {current_score} (Type: {type(current_score)})")
print(f"After: {score_float} (Type: {type(score_float)})")
Execution Result:
Plaintext
Before: 150 (Type: <class 'int'>)
After: 150.0 (Type: <class 'float'>)
As shown, the magnitude of the value remains the same, but the type becomes float, and it is represented as 150.0.
2. Converting Floats to Integers: int()
To convert a floating-point number (float) to an integer (int), use the built-in function int().
Important Note: When converting from float to int, the decimal part is “truncated”. Be aware that it is not rounded.
Syntax:
Python
integer = int(float_number)
Specific Usage Example:
Here is an example where you want to treat measurement data, such as weight, as an integer value.
Python
# Float data
weight_data = 65.85
temperature_data = 36.1
# Convert to int type (decimals are truncated)
weight_int = int(weight_data)
temperature_int = int(temperature_data)
print(f"Original Weight: {weight_data} -> Converted: {weight_int}")
print(f"Original Temp: {temperature_data} -> Converted: {temperature_int}")
Execution Result:
Plaintext
Original Weight: 65.85 -> Converted: 65
Original Temp: 36.1 -> Converted: 36
Although 65.85 would be 66 if rounded, passing it through the int() function results in 65.
If You Want to Round: round()
If you want standard “rounding” instead of simple truncation, use the round() function before using int().
Python
# Round then convert to integer
precise_value = 65.85
# round() returns the nearest integer
rounded_value = round(precise_value)
print(f"Rounded result: {rounded_value} (Type: {type(rounded_value)})")
Execution Result:
Plaintext
Rounded result: 66 (Type: <class 'int'>)
Summary
- float(integer): Converts an integer to a decimal (e.g., 10 -> 10.0).
- int(float): Converts a decimal to an integer. The decimal part is truncated (e.g., 9.9 -> 9).
- Use the round() function if you need rounding.
