How To Round Floats In Python

In Python, we often come across floating-point values that contain many decimal places. While this is useful for high-precision calculations, it can sometimes create clutter and make it difficult to display or use these numbers effectively.

To make the reading and usage of floats more convenient, we can round them off to a specified number of decimal places. In this tutorial, we will discuss different methods for rounding floats in Python.

Method 1: Using the round() Function

Python has a built-in function called round() which can be used to round off floating-point values. The syntax of this function is as follows:

Here, number is the floating-point value we want to round, and ndigits is the number of decimal places to which we want to round the number. If ndigits is not provided, it defaults to 0, and the function returns the nearest integer value.

Let’s see an example:

Output:

3.14

Method 2: Using String Formatting

We can also round floats using string formatting. Here, we use the format specifier f to specify the number of decimal places we want to round the float to. The syntax for this is:

Here, n is the number of decimal places we want to round the float to.

Let’s see an example:

Output:

3.14

Note that this method returns a string representation of the rounded number. If you need the rounded number as a float, you can use the float() function to convert the string back to a float.

Method 3: Using Mathematical Functions

We can also round floats using mathematical functions from the Python math module. The math module provides two functions, floor() and ceil(), which can be used to round down and round up a float respectively. To round a float to a specified number of decimal places, we can make use of these functions along with the following formula:

Let’s see an example:

Output:

3.14
3.15

Full Code

Here’s the full code for all three methods of rounding floats in Python:

Output:

3.14
3.14
3.14
3.15

Conclusion

In this tutorial, we discussed three different methods to round floats in Python: using the round() function, using string formatting, and using mathematical functions from the math module. Depending on your requirements and the situation, you can opt for any of these methods to round your floating-point values in Python.