Rounding Decimals in NumPy A Quick Guide
Rounding decimals is a common operation when working with numerical data.
NumPy offers several ways to round off decimals, each suited for specific
use cases.
Here are the five main methods for rounding numbers in NumPy:
Truncation simply removes the decimal part and returns the integer
closest to zero. You can use either the np.trunc() or np.fix()
functions.
Program:
(Using trunc()):
import numpy as np
arr = np.trunc([-3.1666, 3.6667])
print(arr)
Output:
[-3. 3.]
Program:
(Using fix()):
import numpy as np
arr = np.fix([-3.1666, 3.6667])
print(arr)
Output:
[-3. 3.]
2. Rounding (around)
The np.around() function rounds numbers to a specified number of decimal
places. It follows the typical rounding rule:
If the next digit is ≥ 5, it rounds up.
Otherwise, it rounds down.
Program:
import numpy as np
arr = np.around(3.1666, 2)
print(arr)
Output:
3.17
3. Floor
The np.floor() function rounds numbers down to the nearest integer
(toward negative infinity).
Program:
import numpy as np
arr = np.floor([-3.1666, 3.6667])
arr = np.floor([-3.1666, 3.6667])
print(arr)
Output:
[-4. 3.]
4. Ceil
The np.ceil() function rounds numbers up to the nearest integer (toward
positive infinity).
Program:
import numpy as np
arr = np.ceil([-3.1666, 3.6667])
print(arr)
Output:
[-3. 4.]
More topic in Numpy
