How To Round A Number In Python

In this tutorial, we will learn how to round a number in Python using various methods. Rounding is a common mathematical operation performed when you want to approximate a number to a certain number of decimal places or to an integer.

Python provides various built-in functions and techniques to round numbers, including the round() function, floor(), and ceil() methods from the math module, and the format() function. Let’s dive into the methods step by step.

Step 1: Using the round() function

The round() function is a built-in function in Python that can round a number to the nearest integer or to the specified number of decimals.

The syntax for the round() function is:

The number parameter is the number you want to round, and the optional ndigits parameter specifies the number of decimal places you want to round the number to. If ndigits is omitted, it defaults to 0, and the function rounds the number to the nearest integer.

Here’s some example usage of the round() function:

Output:

3
3.14

Step 2: Using math.floor() and math.ceil() functions

The floor() and ceil() functions from the math module can also round a number to an integer. The floor() function rounds down to the nearest integer less than or equal to the number, while ceil() function rounds up to the nearest integer greater than or equal to the number.

First, you need to import the math module to use the functions:

Here’s an example of using floor() and ceil() functions:

Output:

Floor: 3
Ceil: 4

Moving on to the next method.

Step 3: Using the format() function

The format() function can be used to format a number to a specific number of decimal places. This method doesn’t round the number in the strict sense but allows displaying the number rounded to the desired number of decimal places.

Here’s an example using the format() function:

Output:

3.14

It is essential to note that the format() function returns a string and not a number. To perform mathematical operations with the rounded number, you’ll need to convert it back to a float using the float() function.

Full code

Output:

3
3.14
Floor: 3
Ceil: 4
3.14

Conclusion

In this tutorial, we have covered three methods to round numbers in Python: the round() function, floor() and ceil() functions from the math module, and the format() function. These methods provide different ways to round numbers to integers or decimals, allowing you to choose the most suitable method for your needs.