How To Round Numbers To Nearest Integer In Python

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:

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:

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:

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:

Output:

4
-4

Full Code

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.