NumPy ufunc Rounding Decimals

NumPy provides several ufuncs for rounding array values to a chosen number of decimal places or to the nearest integer boundary.

Rounding Arrays with NumPy ufuncs

Floating-point calculations rarely land on tidy numbers. NumPy gives you a set of ufuncs — around(), floor(), ceil(), and trunc() — that let you clean up decimal values across an entire array in one call, instead of looping through elements with Python's built-in round().

Rounding to Decimal Places with around() and round()

np.around(arr, decimals) rounds every element to the given number of decimal places. np.round() is simply an alias for the same function. A negative decimals value rounds to the left of the decimal point, for example decimals=-1 rounds to the nearest ten.

Example

import numpy as np

arr = np.array([3.1666, 2.5, -1.2345, 7.8999])

# Round to 2 decimal places
rounded = np.around(arr, decimals=2)
print(rounded)
# [ 3.17  2.5  -1.23  7.9 ]

# np.round is an alias for np.around
print(np.round(arr, decimals=0))
# [ 3.  2. -1.  8.]

Flooring, Ceiling and Truncating

np.floor() always rounds down to the nearest integer, np.ceil() always rounds up, and np.trunc() simply chops off the decimal part. They agree for positive numbers but diverge for negative ones, since 'down' means toward negative infinity, not toward zero.

Example

import numpy as np

values = np.array([-3.7, -1.2, 0.0, 2.3, 4.8])

print(np.floor(values))   # [-4. -2.  0.  2.  4.]
print(np.ceil(values))    # [-3. -1.  0.  3.  5.]
print(np.trunc(values))   # [-3. -1.  0.  2.  4.]
  • floor() always rounds toward negative infinity, so negative numbers round further away from zero.
  • ceil() always rounds toward positive infinity, so negative numbers round toward zero instead of away from it.
  • trunc() simply removes the decimal part, always rounding toward zero regardless of sign.
  • around() rounds to the nearest value at a chosen decimal precision, using round-half-to-even for exact ties.
FunctionDirection-2.5 becomes
np.floor()Toward negative infinity-3.0
np.ceil()Toward positive infinity-2.0
np.trunc()Toward zero-2.0
np.around()Nearest, ties to even-2.0
Note: np.around() uses 'round half to even' (banker's rounding) rather than the 'always round .5 up' rule many people learn in school. That means np.around(2.5) gives 2.0 and np.around(3.5) gives 4.0 — both round to the nearest even integer.

Example

import numpy as np

temps_celsius = np.array([21.456, 19.999, -5.501, 30.005])

# Round sensor readings to one decimal place for display
display_temps = np.around(temps_celsius, decimals=1)
print(display_temps)

# Get a safe lower and upper whole-degree bound for each reading
lower_bounds = np.floor(temps_celsius)
upper_bounds = np.ceil(temps_celsius)
print(lower_bounds)
print(upper_bounds)

Exercise: NumPy ufunc Rounding Decimals

What does np.floor(-3.7) return?