NumPy ndarray.round()

The numpy.ndarray.round() method rounds elements in a NumPy array to the specified number of decimal places. It can be applied to the entire array or stored in an alternative output array.

Syntax

</>
Copy
ndarray.round(decimals=0, out=None)

Parameters

ParameterTypeDescription
decimalsint, optionalNumber of decimal places to round to. Default is 0. If negative, it rounds to the left of the decimal point.
outndarray, optionalAlternative output array for storing the result. Must have the same shape as the expected output.

Return Value

Returns an array with rounded values. If out is specified, the result is stored in the provided array.


Examples

1. Rounding Elements to Default (Zero) Decimal Places

This example rounds all elements in an array to the nearest integer.

</>
Copy
import numpy as np

# Create an array with floating-point values
arr = np.array([[1.7, 2.3], [3.8, 4.5]])

# Round to the nearest integer (default decimals=0)
rounded_arr = arr.round()

print(rounded_arr)

Output:

[[2. 2.]
 [4. 4.]]

The values are rounded to the nearest integer, with .5 rounding to the nearest even number.

2. Specifying Decimal Places in ndarray.round()

Here, we round elements to a specified number of decimal places.

</>
Copy
import numpy as np

# Create an array with floating-point values
arr = np.array([[1.257, 2.678], [3.145, 4.999]])

# Round to two decimal places
rounded_arr = arr.round(decimals=2)

print(rounded_arr)

Output:

[[1.26 2.68]
 [3.14 5.  ]]

Each element is rounded to two decimal places while maintaining array structure.

3. Rounding to a Negative Decimal Place

Negative decimals rounds to the left of the decimal point.

</>
Copy
import numpy as np

# Create an array with integer values
arr = np.array([[123, 678], [915, 432]])

# Round to the nearest tens place (decimals=-1)
rounded_arr = arr.round(decimals=-1)

print(rounded_arr)

Output:

[[120 680]
 [920 430]]

Each number is rounded to the nearest multiple of 10.

4. Storing the Result in an Output Array

The result can be stored in an existing output array.

</>
Copy
import numpy as np

# Create an array with floating-point values
arr = np.array([2.76, 3.49, 4.51])

# Create an output array of the same shape
out_arr = np.empty_like(arr)

# Round and store the result in out_arr
arr.round(decimals=1, out=out_arr)

print(out_arr)

Output:

[2.8 3.5 4.5]

The rounded values are stored in out_arr, avoiding additional memory allocation.