Wednesday, July 3, 2024
HomeLanguagesPythonHow to round array elements to the given number of decimals using...

How to round array elements to the given number of decimals using NumPy?

In NumPy, we can round array elements to the given number of decimals with the help of round(). 

Syntax:

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

The first parameter will be an array and the second parameter will be the number of decimals for which needed rounded. If no parameter will be pass as the second parameter then by default it takes 0. It will return round array elements to the given number of decimals.

Example 1:

Python3




import numpy as np
  
  
# perform the numpy.round
rounded_array = np.round([1.5, 1.53, 1.23, 3.89])
  
# print the rounded_array
print(rounded_array)


Output

[2. 2. 1. 4.]

Example 2:

Python3




import numpy as np
  
  
# perform the numpy.round
rounded_array = np.round([1.5, 1.53, 1.23, 3.89], 
                         decimals=1)
  
# print the rounded_array
print(rounded_array)


Output:

[1.5 1.5 1.2 3.9]

Example

Python3




import numpy as np
  
  
# perform the numpy.round
rounded_array = np.round(
    [1.534, 1.5389, 1.2301, 3.89903, 6.987, 4.09], decimals=2)
  
# print the rounded_array
print(rounded_array)


Output:

[1.53 1.54 1.23 3.9  6.99 4.09]

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments