np.round() Function in Python

While working on a data analysis project, I needed to round decimal values consistently across large NumPy arrays. The issue is that while Python has the built-in round() function, it doesn’t always work ideally with NumPy arrays and can behave unexpectedly with certain decimal values. This is where NumPy’s np.round() function becomes incredibly useful.

In this article, I’ll cover several ways to use np.round() effectively in your Python projects (with both simple examples and real-world applications).

So let’s dive in!

Basic Usage of np.round() Function

NumPy’s round function (often written as np.round() or numpy.round()) lets you round Python arrays of numbers to a specified decimal place. Here’s how to use it in its simplest form:

import numpy as np

# Simple array example
arr = np.array([3.14159, 2.71828, 1.41421])
rounded = np.round(arr, 2)
print(rounded)

Output:

[3.14 2.72 1.41]

I executed the above example code and added the screenshot below.

np.round

The basic syntax is simple:

np.round(a, decimals=0, out=None)

Where:

  • a is the input array
  • decimals is the number of decimal places to round to (default is 0)
  • out is an optional output array where the results can be stored

This function rounds elements of an array to the nearest value with the given number of decimals. If you don’t specify the decimals parameter, it rounds to the nearest integer.

Read Copy a NumPy Array to the Clipboard through Python

Advanced Rounding Options in NumPy

NumPy offers several variations of rounding that give you more control over your data:

1. Round Multidimensional Arrays

One of the strengths of np.round() is handling multidimensional arrays in Python:

# 2D array example - sales data by quarter and region
sales_data = np.array([
    [1234.567, 2345.678, 3456.789],  # Q1 sales for 3 regions
    [4567.891, 5678.912, 6789.123]   # Q2 sales for 3 regions
])

# Round to nearest dollar
rounded_sales = np.round(sales_data, 0)
print(rounded_sales)

Output:

[[1235. 2346. 3457.]
 [4568. 5679. 6789.]]

I executed the above example code and added the screenshot below.

numpy round

NumPy’s np.round() can handle complex, multi-dimensional data effortlessly. This makes rounding datasets like financials or metrics across regions or time very efficient.

Check out NumPy Divide Array by Scalar in Python

2. Different Decimal Places for Different Dimensions

You can even round different axes of your array to different decimal places using the decimals parameter as an array in Python:

# Temperature readings (fahrenheit) with excess precision
temps = np.array([
    [98.6123, 99.2376, 101.4826],
    [97.8245, 98.1123, 98.6421]
])

# Round first row to 1 decimal, second row to 2 decimals
decimals_by_row = np.array([1, 2])
rounded_temps = np.zeros_like(temps)

for i in range(len(temps)):
    rounded_temps[i] = np.round(temps[i], decimals_by_row[i])

print(rounded_temps)

Output:

[[98.6 99.2 101.5]
 [97.82 98.11 98.64]]

I executed the above example code and added the screenshot below.

np round

You can customize rounding precision across rows or columns by iterating with np.round(). This flexibility is useful when different data segments require different levels of accuracy.

Read np.unit8 in Python

3. Round to Multiples

Sometimes you need to round to the nearest 5, 10, or any other number rather than decimal places:

# Round prices to nearest 5 cents for a pricing strategy
prices = np.array([9.97, 24.32, 49.99, 99.73])
rounded_nickels = np.round(prices * 20) / 20  # Multiply by 20, round, divide by 20
print(rounded_nickels)  # Output: [10.   24.3  50.   99.75]

NumPy allows rounding to custom multiples (like 5 cents) with simple scaling math. This is especially handy in pricing or binning tasks in data preprocessing.

Check out the NumPy Unique Function in Python

4. np.round() vs. Python’s Built-in round()

There are important differences between NumPy’s round and Python’s built-in round:

# Python's round uses "banker's rounding" for ties
print(round(2.5))  # Output: 2
print(round(3.5))  # Output: 4

# NumPy rounds to nearest even integer (also banker's rounding)
print(np.round(2.5))  # Output: 2.0
print(np.round(3.5))  # Output: 4.0

# But NumPy works on entire arrays at once
numbers = np.array([1.5, 2.5, 3.5, 4.5])
print(np.round(numbers))  # Output: [2. 2. 4. 4.]

# Python's round would require a loop
rounded = [round(num) for num in numbers]
print(rounded)  # Output: [2, 2, 4, 4]

Another key difference is that np.round() preserves the data type, while Python’s round() converts to integers when decimals=0:

# Python's round
x = 3.7
y = round(x)
print(y, type(y))  # Output: 4 <class 'int'>

# NumPy's round
z = np.round(x)
print(z, type(z))  # Output: 4.0 <class 'numpy.float64'>

Read Create a 2D NumPy Array in Python

Real-World Applications

Let’s look at some practical examples where np.round() is especially useful:

1. Financial Analysis

When working with financial data, precise rounding is crucial:

# Stock price movements over a week
stock_changes = np.array([0.0823, -0.0412, 0.0256, -0.0187, 0.0495])

# Calculate percentage changes rounded to 2 decimal places
percent_changes = np.round(stock_changes * 100, 2)
print(f"Daily stock price changes: {percent_changes}%")
# Output: Daily stock price changes: [ 8.23 -4.12  2.56 -1.87  4.95]%

# Calculate total change
total_change = np.round(np.sum(stock_changes) * 100, 2)
print(f"Weekly change: {total_change}%")
# Output: Weekly change: 9.75%

Rounding financial metrics like stock price changes improves clarity and reporting accuracy. Using np.round() ensures consistent formatting across percentage and total calculations.

Read NumPy Normalize 0 and 1 in Python

2. Data Visualization Preparation

When preparing data for visualization, rounding can make your charts more readable:

# Monthly temperature data for New York (°F)
monthly_temps = np.array([
    32.1, 34.2, 42.8, 52.3, 62.1, 71.5,
    76.8, 75.3, 67.9, 57.1, 47.2, 36.5
])

# Round for display on chart labels
display_temps = np.round(monthly_temps)
print(f"Temperatures for chart: {display_temps}")
# Output: Temperatures for chart: [32. 34. 43. 52. 62. 72. 77. 75. 68. 57. 47. 36.]

# Convert to Celsius and round to 1 decimal place
celsius_temps = np.round((monthly_temps - 32) * 5/9, 1)
print(f"Celsius temperatures: {celsius_temps}")
# Output: Celsius temperatures: [ 0.1  1.2  6.  11.3 16.7 21.9 24.9 24.1 19.9 13.9  8.4  2.5]

Rounding data before plotting enhances readability and improves user understanding of charts. It also allows smooth conversions (e.g., to Celsius) while maintaining a clean visual format.

Check out ValueError: setting an array element with a sequence error in Python

3. Scientific Computing

In scientific work, controlling precision is often necessary:

# Experimental measurements with excess precision
measurements = np.array([
    [10.12345, 11.54321, 9.87654],
    [12.13579, 8.97531, 10.54321]
])

# Round based on instrument precision (±0.1)
results = np.round(measurements, 1)
print("Experimental results:")
print(results)
# Output:
# Experimental results:
# [[10.1 11.5  9.9]
#  [12.1  9.  10.5]]

Scientific measurements often demand rounding based on instrument precision or error margins. np.round() provides a straightforward way to align results with required precision standards.

The np.round() function is an essential tool in any data scientist‘s toolkit. While Python’s built-in round() works for simple cases, NumPy’s version offers better performance with arrays and consistent behavior across your numerical data.

When working with large datasets or when precision matters, reach for np.round(). It’s fast, flexible, and handles those edge cases that might otherwise cause subtle bugs in your analysis.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.