Python round() Function



The Python round() function is used to round the given floating point number to the nearest integer value. The round is done with the specified number of decimal points. If the number of decimal places to round is not specified, it will round to the nearest integer, which is considered as 0.

For instance, if you wish to round a number, let's say 6.5. It will be rounded to the nearest  integer, which is 7. However, the number 6.86 will be rounded to one decimal place to give the number 6.9.

Syntax

Following is the syntax of Python round() function −

round(x[,n])

Parameters

  • x − This is the number to be rounded.

  • n (optional) − This is the number of decimal points to which the given number will be rounded. It's default value is 0.

Return Value

This function returns the number rounded to the specified digits from the decimal point.

Example

The following example shows the usage of the Python round() function. Here the number to be rounded and the number of decimal points to which the number will be rounded is passed as an argument to the round() function.

print ("round(80.23456, 2) : ", round(80.23456, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))

When we run above program, it produces following result −

round(80.23456, 2) :  80.23
round(100.000056, 3) :  100.0

Example

In here the number of decimal points to which the given number will be rounded is not present. Hence, it's default value 0 is taken.

# Creating the number
num = 98.65787
res = round(num)
# printing the result
print ("The rounded number is:",res)

While executing the above code we get the following output −

The rounded number is: 99

Example

If we pass a negative number as an argument, a negative closest number is returned by this function.

In this example an objet 'num' is created with the value '-783.8934771743767623'. The decimal points to which the given value will be rounded is '6'. Then the round() function is used to retrieve the result.

# Creating the number
num = -783.8934771743767623
decimalPoints = 6
res = round(num, decimalPoints)
# printing the result
print ("The rounded number is:",res)

Following is an output of the above code −

The rounded number is: -783.893477

Example

In the example given below an array is created. To round arrays in Python we have used the numpy module. Then this array is passed as an argument to the round() function with 4 decimal points to be rounded.

import numpy as np
# the arrray
array = [7.43458934, -8.2347985, 0.35658789, -4.557778, 6.86712, -9.213698]
res = np.round(array, 4)
print('The rounded array is:', res)

Output of the above code is as follows −

The rounded array is: [ 7.4346 -8.2348  0.3566 -4.5578  6.8671 -9.2137]
python_built_in_functions.htm
Advertisements