Python Programming (138 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (32 Blogs)
  • Data Science (26 Blogs)
  • Mastering Python (92 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

How To Implement Round Function In Python?

Last updated on Apr 24,2020 3.7K Views

43 / 62 Blog from Python Fundamentals

Round function in Python, returns a floating point number that is a rounded version of the specified number. This article will explore the concept in detail Following pointers will be covered in this article,

So let us get started then,

Round Function In Python

The method round(x, n) will return value x rounded to n digits after the decimal point.

Example:
round(7.6 + 8.7,1)

Output:
16.3

Round gives this ability to give the closest value

Example:
round(6.543231, 2)

Output:
6.54

Sometimes it doesn’t give the correct output

Example:
round(2.675, 2) #should return 2.68 but it doesn’t

Output:
2.67

Sometimes it gives the correct output

Example:
round(8.875, 2)

Output:
8.88

Moving on with this article on Round Function In Python.

Python round()

Round function in python rounds off the decimal value to a given number of digits, if we don’t provide n i.e the number of digits after decimal it will round off the number to the nearest integer.

It will round off to ceil if the integer after that is >= 5 and to floor integer, if the decimal is < 5 .
round() without the second parameter

#int
print(round(12))
#float
print(round(66.6))
print(round(45.5))
print(round(92.4))

Output:
12
67
46
92

Now if the second parameter is provided then last decimal digit will be increased by 1 till the rounded value if last_digit+1 is >= 5 else it will be same as provided.

round() with the second parameter

# when last_digit+1 =5
print(round(3.775, 2))
# when last_digit+1 is >=5
print(round(3.776, 2))
# when if last_digit+1 is <5
print(round(3.773, 2))

Output:
3.77
3.78
3.77

Moving on with this article on Round Function In Python.

Practical Applications:

Some of the applications of round functions are rounding digits to limited numbers, for example, we usually take 2 or 3 numbers after decimal also if we want to represent fractions to decimal so that we can represent fraction accurately.

b=2/6
print(b)
print(round(b, 2))

Output:
0.3333333333333333
0.33

In this era of data science and computing we often store data as Numpy array or as pandas data frame where rounding plays a very important role in order to compute operations accurately, similar to round function in python Numpy or Pandas take two arguments data and digits i.e the data which we want to round and how many digits we have to round after decimal and it applies this to all the rows and columns. let’s look at some examples.

Moving on with this article on Python: Round Function.

Rounding NumPy Arrays

To install NumPy you can use:

pip3 install numpy

Other than that if you are using Anaconda environment it will be already installed, to round all the values of NumPy array we will pass data as an argument to np.around() function.
Now we will create a NumPy array of 3×4 size containing floating-point numbers as below:

import numpy as np
np.random.seed(444)
data = np.random.randn(3, 4)
print(data)

Output:
[[ 0.35743992 0.3775384 1.38233789 1.17554883]
[-0.9392757 -1.14315015 -0.54243951 -0.54870808]
[ 0.20851975 0.21268956 1.26802054 -0.80730293]]

For example, the following rounds all of the values in data to three decimal places:

import numpy as np
np.random.seed(444)
data = np.random.randn(3, 4)
print(np.around(data, decimals=3))

Output:
[[ 0.357 0.378 1.382 1.176]
[-0.939 -1.143 -0.542 -0.549]
[ 0.209 0.213 1.268 -0.807]]

np.around() can be used to correct the floating-point error.

we can see in the following example that element at 3×1 is 0.20851975 you expect the value to be 0.208 but it is rounded to 0.209 also you can see that the value at 1×2 is rounded correctly to 0.378.

So, if there is a need of rounding data to required form NumPy has many methods:

  • numpy.ceil()
  • numpy.floor()
  • numpy.trunc()
  • numpy.rint()

The np.ceil() function rounds every value in the array to the nearest integer greater than or equal to the original value:

print(np.ceil(data))

Output:
[[ 1. 1. 2. 2.]
[-0. -1. -0. -0.]
[ 1. 1. 2. -0.]]

To round every value down to the nearest integer, use np.floor():

print(np.floor(data))

Output:
[[ 0. 0. 1. 1.]
[-1. -2. -1. -1.]
[ 0. 0. 1. -1.]]

You can also truncate each value to its integer component with np.trunc():

print(np.trunc(data))

Output:
[[ 0. 0. 1. 1.]
[-0. -1. -0. -0.]
[ 0. 0. 1. -0.]]

Finally, to round to the nearest integer using the “rounding half to even” strategy, use np.rint():

print(np.rint(data))

Output:
[[ 0. 0. 1. 1.]
[-1. -1. -1. -1.]
[ 0. 0. 1. -1.]]

Moving on with this article on Python: Round Function.

Rounding Pandas Series and DataFrame

Pandas is another popular library for data scientists which is used to analyze data.

Similar to NumPy we can install this library using the following command:

pip3 install pandas

The two main data structure of Pandas are DataFrame and Series, DataFrame is basically like a table in database and Series is a column. We can round objects using Series.round() and DataFrame.round().

import pandas as pd
import numpy as np
np.random.seed(444)
series = pd.Series(np.random.randn(4))
print(series)

Output:
0 0.357440
1 0.377538
2 1.382338
3 1.175549
dtype: float64
print(series.round(2))
0 0.36
1 0.38
2 1.38
3 1.18
dtype: float64

Moving on with this article on Python: Round Function

DataFrame:

import pandas as pd
import numpy as np
np.random.seed(444)
df = pd.DataFrame(np.random.randn(3, 3), columns=["Column 1", "Column 2", "Column 3"])
print(df)
print(df.round(3))

Output:
Column 1 Column 2 Column 3
0 0.357440 0.377538 1.382338
1 1.175549 -0.939276 -1.143150
2 -0.542440 -0.548708 0.208520
Column 1 Column 2 Column 3
0 0.357 0.378 1.382
1 1.176 -0.939 -1.143
2 -0.542 -0.549 0.209

For DataFrame we can specify different precision for each column thus, the round function of can accept a dictionary or Series so that we can provide different precision for different columns.

print(df.round({“Column 1”: 1, “Column 2”: 2, “Column 3”: 3}))

Output:
Column 1 Column 2 Column 3
0 0.4 0.38 1.382
1 1.2 -0.94 -1.143
2 -0.5 -0.55 0.209

Summary
In this article, we covered what is round function and how it is implemented from the core in python. We also covered some downsides of round function and how we can correct them and how that can be useful in libraries that are widely used in data science.

Thus we have come to an end of this article on ‘Round Function In Python’. With the increasing popularity, the demand has also increased in domains like machine learning, artificial intelligence, data science, etc. To master your skills enroll in edureka’s python certification program and kick-start your learning.

Have any questions? Mention them in the comments. We will get back to you as soon as possible

Upcoming Batches For Python Certification Training Course
Course NameDate
Python Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Python Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Python Certification Training Course

Class Starts on 25th March,2023

25th March

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Implement Round Function In Python?

edureka.co