In this tutorial, you will learn how to round numbers to the nearest integer in Python using various methods such as the round() function, math.floor(), math.ceil(), and int() function. Rounding numbers is a common task in various applications related to mathematics, finance, and data manipulation.
Step 1: Using the round() Function
The built-in round() function in Python takes a number as its input and returns the nearest integer value. It also takes an optional second argument for specifying the number of decimal places.
Here’s how to use the round() function:
1 2 3 |
number = 4.6 rounded_number = round(number) print(rounded_number) |
Output:
5
Step 2: Using math.floor() Function
For rounding down to the nearest integer, you can use the math.floor() function available in the math module. This function returns the largest integer less than or equal to the given number.
First, you need to import the math module in your Python script:
1 2 3 4 5 |
import math number = 4.6 rounded_number = math.floor(number) print(rounded_number) |
Output:
4
Step 3: Using math.ceil() Function
If you want to round up to the nearest integer, you can use the math.ceil() function, also available in the math module. This function returns the smallest integer greater than or equal to the given number.
Here’s how to use the math.ceil() function:
1 2 3 4 5 |
import math number = 4.6 rounded_number = math.ceil(number) print(rounded_number) |
Output:
5
Step 4: Using int() Function
Using the built-in int() function always rounds down the given number, similar to the math.floor() function. However, it only works for positive numbers. If you have a negative number, the int() function rounds down away from zero.
Look at the examples below:
1 2 3 4 5 6 7 8 |
positive_number = 4.6 negative_number = -4.6 rounded_positive_number = int(positive_number) rounded_negative_number = int(negative_number) print(rounded_positive_number) print(rounded_negative_number) |
Output:
4 -4
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import math # Using round() function number = 4.6 rounded_number = round(number) print(rounded_number) # Using math.floor() function rounded_number = math.floor(number) print(rounded_number) # Using math.ceil() function rounded_number = math.ceil(number) print(rounded_number) # Using int() function positive_number = 4.6 negative_number = -4.6 rounded_positive_number = int(positive_number) rounded_negative_number = int(negative_number) print(rounded_positive_number) print(rounded_negative_number) |
Output:
5 4 5 4 -4
Conclusion
In this tutorial, you have learned various methods to round numbers to the nearest integer in Python, including the round() function, math.floor(), math.ceil(), and int() function. These methods can be applied in different situations based on the desired rounding behavior.