When you do any calculation using the float value and print its output then you will see the number of digits after the decimal is very long. Thus it bothered someone who does not want the long digits. They want to round float to some digits. In this entire tutorial of ” How to”, you will know how to round floats in python using various methods.
How Floats Look Without Rounding
Let’s say I have a float variable and an integer variable. When I perform calculations like multiplication and print its output then I will get the output as below.
float_value = 1.23456
int_value = 11
mul = int_value * float_value
You can see the number of digits after the decimal point is very large. That’s why we prefer rounding of digits. In the next section, you will know all the methods for Round Floats in Python.
How to round off float in python: Methods
Method 1: Round Float value using the round() method
There is a function in python that allows you to round any float value. And it is round(). The syntax of it is below.
How to round float to 2 decimal places in python
Let’s say I want to round the above multiplication results to up to 2 digits, then I will use the following code.
# round method
In the same way, just use 3 to round the float value to 3 digits.
Method 2 : Using str.format()
The second method to round float value is using the python str.format() method. It has two parts one is a string and the other, format() method. The syntax for using it is below.
If I apply it to the same multiplication results then I will get the output as below.
# using str.format() method
Method 3: Round Float Value using NumPy
The last method to round float values in python is using NumPy. Numpy is a python module that has a function np.round() that is the same method as python round(). But in numpy.round() all values are treated as a NumPy array. Using the same example, I will use the numpy.round() method on the multiplication results.
import numpy as np
Rounding the float value is a must if you want to find the approximate results of any calculation. These are the methods I have compiled for you to round any float value. If you want to add any other methods then you can contact us. And if you have other queries then you can directly message us on the Offical Data Science Learner Facebook Page.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.