NumPy round()

The round() function returns floating-point elements of an array to the nearest integer or rounded to the specified number of decimals.

Example

import numpy as np

# create an array
array1 = np.array([1.2, 2.7, 3.5, 4.1, 5.9])

# use round() to round the elements of the array to the nearest integer rounded_array = np.round(array1)
# print the rounded array print(rounded_array) # Output : [1. 3. 4. 4. 6.]

round() Syntax

The syntax of round() is:

numpy.round(array, decimals=0, out=None)

round() Arguments

The round() function takes one argument:

  • array - the input array whose elements are to be rounded
  • decimal (optional) - number up to which the elements of array is rounded
  • out (optional) - the output array where the result will be stored.

round() Return Value

The round() function returns a new array with the rounded values.


Example 1: Round Array Elements to Nearest Integer

import numpy as np

# create a 2-D array
array1 = np.array([[1.2, 2.7, 3.5],
                                [4.1, 5.9, 6.4]])

# use round() to round the elements of the array to the nearest integer rounded_array = np.round(array1)
print(rounded_array)

Output

[[1. 3. 4.]
 [4. 6. 6.]]

In this example, the np.round() function rounds the elements of the array to the nearest integer.

However, even after rounding, the data type of the array remains as float64. That is the reason for the presence of a decimal point in the output.

If you prefer to have the output as integers without the decimal points, you can convert the data type of the rounded array to int using astype() as:

rounded_array = np.round(array1).astype(int)

Then the output will be,

[[1 3 4]
 [4 6 6]]

Example 2: Round Elements to Given Number of Decimal Places

import numpy as np

# create an array
array1 = np.array([1.23456789, 2.3456789, 3.456789])

# round the elements to 2 decimal places
rounded_array = np.round(array1, decimals=2)

print(rounded_array)

Output

[1.23 2.35 3.46]

Each element in array1 is rounded to 2 decimal places as specified by the decimals argument in the np.round() function.


Example 3: Use of out Argument in round()

import numpy as np

# create an array 
array1 = np.array([1.2, 2.7, 3.5])

# create an empty array with the same shape as array1
rounded_array = np.zeros_like(array1)

# round the elements of array1 and store the result in rounded_array np.round(array1, out=rounded_array)
print(rounded_array)

Output

[1. 3. 4.]

Here, after specifying out=rounded_array, the rounded_array contains the rounded values of each element in array1.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges