The Wayback Machine - https://web.archive.org/web/20241126022635/https://www.geeksforgeeks.org/round-function-python/
Open In App

round() function in Python

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python round() function is a built-in function available with Python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer. In this article, we will see Python how to Round Numbers using round() function.

Python round() Function Syntax

Syntax : round(number, number of digits)

Parameters : 

  • number : number to be rounded
  • number of digits (Optional) : number of digits up to which the given number is to be rounded.

If the second parameter is missing, then the round() function returns: 

  1. if only an integer is given, for instance, 15, then it will round off to 15 itself.
  2. if a decimal number is given, then it will round off to the closest multiple of 10 to the power minus ndigits.

Returns : The round() function always returns a number that is either a float or an integer.

Python round() Function with Examples

The `round()` function in Python is used to round numbers. It takes two parameters: the number to be rounded and, optionally, the number of decimal places. If no decimal places are specified, it rounds to the nearest integer. The function follows standard rounding rules.

There are various method in Python how to Round Numbers, here we are explaining some generally used method which we used to round() function.

  • Round Numbers Using Python round() Function
  • Python round() function if the Second parameter is Missing
  • Python round() function if the Second Parameter is Present
  • Round Number with Math Library in Python
  • Rounding Number with Numpy Module in Python
  • Round Up Numbers in Python
  • Round Down Numbers

Python round() Function

In this example, we are using the round function for the number 111.23 in Python.

Python
number = 111.23
rounded_number = round(number)
print(rounded_number)

Output :

111

Python Round() Function if the Second Parameter is Missing

In the given example, we have rounded off the 51.6,51.5,51.4 in Python.

Python
# for integers
print(round(15))

# for floating point
print(round(51.6))
print(round(51.5))
print(round(51.4))

Output: 

15
52
52
51

When the second parameter is present, then it returns: 

The last decimal digit till which it is rounded is increased by 1 when (ndigit+1)th digit is >=5, else it stays the same.

Python round() Function if the Second Parameter is Present

In the given example, we have rounded off the different numbers to the digit 2 decimal places.

Python
# when the (ndigit+1)th digit is =5
print(round(2.665, 2))

# when the (ndigit+1)th digit is >=5
print(round(2.676, 2))

# when the (ndigit+1)th digit is <5
print(round(2.673, 2))

Output: 

2.67
2.68
2.67

Python round() with Negative Integers 

In the given example, round(-3.2) is converted into -3 is the nearest integer to -3.2. Similarly, round(-4.7) returns -5 since -5 is closer to -4.7 than -4. Similarly round(-2.5) returns -2 because it rounds down when the decimal part is exactly 0.5. Same as the fourth example demonstrates using the ndigits parameter with a negative number. round(-2.675, 2) returns -2.67.Similarly, round(-1234, -2), returns -1200 because it rounds to the nearest hundred, which is in the negative direction.

Python
print(round(-3.2))  
print(round(-4.7)) 
print(round(-2.5)) 
print(round(-2.675, 2))
print(round(-1234, -2))

Output :

-3
-5
-2
-2.67
-1200

Round Number with Math Library in Python

By default, round() rounds a number to the nearest integer. However, you can also specify whether to round up or down using the round() function in combination with the math module.

In the given example, we are rounding up and rounding down the number 3.6 in Python.

Python
import math

num = 3.6
rounded_num = math.floor(num) # rounds down to nearest integer
print(rounded_num) # output: 3

rounded_num = math.ceil(num) # rounds up to nearest integer
print(rounded_num) # output: 4

Output :

3
4

Rounding Number with Numpy Module in Python

In this example, we are using numpy module to round the values to their 3rd decimal places in Python.

Python
import numpy as np

arr = np.array([-2.675, -1.23456789, -3.14159265])
rounded_arr = np.round(arr, decimals=3)

print(rounded_arr)

Output :

[-2.675 -1.235 -3.142]

Round Up Numbers in Python

In the given example, we have rounded off the number 12.7.

Python
print(round(12))
print(round(12.7))

Output:

12
13

Python how to Round Down Numbers

In the given example, we have rounded off the numbers 12.1,12.4,12.5.

Python
print(round(12))
print(round(12.1))
print(round(12.4))
print(round(12.5))

Output:

12
12
12
12

Error and Exceptions

TypeError: This error is raised in the case when there is anything other than numbers in the parameters. 

Python
print(round("a", 2))

Output: 

Runtime Errors:
Traceback (most recent call last):
File "/home/ccdcfc451ab046030492e0e758d42461.py", line 1, in
print(round("a", 2))
TypeError: type str doesn't define __round__ method

Practical Applications

One of the common uses of rounding functions is Handling the mismatch between fractions and decimals. We usually work with just two or three digits to the right of the decimal point when there is no exact equivalent to the fraction in decimal.

Python
# practical application
b = 1/3
print(b)
print(round(b, 2))

Output: 

0.3333333333333333
0.33

Note: In Python, if we round off numbers to floor or ceil without giving the second parameter, it will return 15.0 for example and in Python 3 it returns 15, so to avoid this we can use (int) type conversion in Python. It is also important to note that the round ()function shows unusual behaviour when it comes to finding the mean of two numbers. 

round() function in Python – FAQs

What is the Round Function in Python?

The round() function in Python is a built-in function used to round a floating-point number to a specified number of decimal places. The default behavior without specifying decimal places rounds to the nearest whole number.

Syntax:

round(number, ndigits)
  • number: the number you want to round.
  • ndigits: the number of decimal places to round to. If omitted, it rounds to the nearest whole number.

What is the Use of round()?

The primary use of round() is to reduce the number of decimal places to a more manageable or required level for display, calculation, or further processing. This function helps in controlling the precision of floating-point arithmetic and is commonly used in financial calculations, data summaries, and graphical data representations.

What is Round Formula Function?

In programming, the “round formula” typically refers to the algorithm used by the round() function to determine how to round a given number to the nearest value with the specified precision. In Python:

  • If the decimal part of the number is less than 0.5, the number is rounded down.
  • If the decimal part of the number is 0.5 or more, the number is rounded up.

What is Round and ABS Function in Python?

  • round(): As described, it’s used for rounding numbers to a specified precision.
  • abs(): The abs() (absolute) function in Python returns the absolute value of a given number. The absolute value of a number is its non-negative value without regard to its sign. For instance, abs(-7.25) returns 7.25.

Example of round() and abs():

print(round(3.7564, 2))  # Rounds to 3.76
print(abs(-3.7564)) # Returns 3.7564

Why Does Python Round 0.5 to 0?

Python uses a method called “rounding half to even” for its round() function. When a value is exactly halfway between two integers, it rounds to the nearest even integer. This method reduces bias in rounding that can accumulate in statistical processes and is the default method in many programming languages.

Example of Rounding 0.5 in Python:

print(round(0.5))  # Returns 0
print(round(1.5)) # Returns 2


Previous Article
Next Article

Similar Reads

Pandas DataFrame round() Method | Round Values to Decimal
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier.  Pandas round() function rounds a DataFrame value to a number with given decimal places. This function provides the flexibility to round differe
2 min read
Pandas Series dt.round | Round Off DateTime Values to Given Frequency
The Pandas dt.round() method rounds off the DateTime values in a series to a certain frequency level.Example:Python3import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result = sr
2 min read
Python | Pandas Series.round()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.When doing mathematical operations on series, many times the returned series is having decimal values and decimal values could go to upto
2 min read
Python | Pandas DatetimeIndex.round()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.round() function localize tz-naive DatetimeIndex to tz-aware DatetimeIndex. This method takes a time zone (tz) naiv
2 min read
Python | Pandas TimedeltaIndex.round
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.round() function round the labels of the given TimedeltaIndex object to the specified frequency. Syntax : Timedelt
2 min read
Python | Pandas Timestamp.round
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.round() function is used to round the given Timestamp to the specified resolution. Syntax :Timestamp.round() Parameters
2 min read
Python | Numpy matrix.round()
With the help of Numpy matrix.round() method, we are able to round off the values of the given matrix. Syntax : matrix.round() Return : Return rounded values in matrix Example #1 : In the given example we are able to round off the given matrix by using matrix.round() method. # import the important module in python import numpy as np # make matrix w
1 min read
Ceil and floor of the dataframe in Pandas Python – Round up and Truncate
In this article, we will discuss getting the ceil and floor values of the Pandas Dataframe. First, Let's create a dataframe. Example: C/C++ Code # importing pandas and numpy import pandas as pd import numpy as np # Creating a DataFrame df = pd.DataFrame({'Student Name': ['Anuj', 'Ajay', 'Vivek', 'suraj', 'tanishq', 'vishal'], 'Marks': [55.3, 82.76,
2 min read
How to Round Numbers in Python?
In this article, we will discuss How to Round Numbers in Python with suitable methods and examples of How to round up in Python. Example: Input: 3.5 Output: 4 Explanation: Nearest whole number. Input: 3.74 Output: 3.7 Explanation: Rounded to one decimal place.Round Up Numbers in PythonRounding a number means making the number simpler by keeping its
9 min read
PyQt5 – Round indicator of CheckBox
In this article we will see how to create round indicator of check box. By default, check box have square indicator although with the help of style sheet we can change it make it round. Below is the representation of normal indicator vs the round indicator of check box. In order to do this we have to do the following : Setting up the border to indi
2 min read
PyQt5 - How to make Round Radio Button ?
In this article we will see how to create round radio button. By default the shape of radio button is rectangular although if we set width equal to the height it become square. Below is the representation of normal bordered radio button vs the radio button round in shape. In order to do this we have to do the following : 1. Create a radio button. 2
2 min read
Methods to Round Values in Pandas DataFrame
There are various ways to Round Values in Pandas DataFrame so let's see each one by one: Let's create a Dataframe with 'Data Entry' Column only: Code: C/C++ Code # import Dataframe class # from pandas library from pandas import DataFrame # import numpy library import numpy as np # dictionary Myvalue = {'DATA ENTRY': [4.834327, 5.334477, 6.89, 7.645
3 min read
How to round elements of the NumPy array to the nearest integer?
Prerequisites: Python NumPy In this article, let's discuss how to round elements of the NumPy array to the nearest integer. numpy.rint() function of Python that can convert the elements of an array to the nearest integer. Syntax: numpy.rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) =
1 min read
How to round array elements to the given number of decimals using NumPy?
In NumPy, we can round array elements to the given number of decimals with the help of round(). Syntax: np.round(a, decimals=0, out=None) The first parameter will be an array and the second parameter will be the number of decimals for which needed rounded. If no parameter will be pass as the second parameter then by default it takes 0. It will retu
1 min read
How to round a number in SQLAlchemy and MySQL?
In this article, we are going to round a number using SQLAlchemy and MySQL. Database related information : We have used a mysql database along with a table named "student". Database used : geeksforgeeks Table used : studentsRequirements : We need MySQL installed along the with "SQLAlchemy" module and "pymysql" module ( a dependency of SQLAlchemy we
3 min read
Program to calculate the Round Trip Time (RTT)
Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgment of that signal to be received. This time, therefore, consists of the propagation times between the two-point of the signal. On the Internet, an end-user can determine the RTT to and from an IP(Internet Protocol) address
2 min read
Pandas Series dt.floor() | Round DateTime Values to Nearest Frequency
The dt.floor() method performs floor operation on the data to the specified frequency. This is useful when we want to round down the DateTime data to a specific frequency level, such as hourly (‘H’), daily (‘D’), monthly (‘M’), etc. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010
2 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | askopenfile() function in Tkinter
While working with GUI one may need to open files and read data from it or may require to write data in that particular file. One can achieve this with the help of open() function (python built-in) but one may not be able to select any required file unless provides a path to that particular file in code. With the help of GUI, you may not require to
2 min read
Python | Binding function in Tkinter
Tkinter is a GUI (Graphical User Interface) module that is widely used in desktop applications. It comes along with the Python, but you can also install it externally with the help of pip command. It provides a variety of Widget classes and functions with the help of which one can make our GUI more attractive and user-friendly in terms of both look
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modulus of mod on the result of x**y (i.e.: x**y % mod
2 min read
ord() function in Python
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a U
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
Practice Tags :
three90RightbarBannerImg