To round to nearest integer towards zero, use the numpy.fix() method in Python Numpy. It rounds an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats. The 1st parameter, x is an array of floats to be rounded. The 2nd parameter, out is a location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated array is returned.
The method returns a float array with the same dimensions as the input. If second argument is not supplied then a float array is returned with the rounded values. If a second argument is supplied the result is stored there. The return value out is then a reference to that array.
Steps
At first, import the required library −
import numpy as np
Create an array with float type using the array() method −
arr = np.array([120.6, -120.6, 200.7, -320.1, 320.1, 500.6])
Displaying our array −
print("Array...\n",arr)Get the datatype −
print("\nArray datatype...\n",arr.dtype)
Get the dimensions of the Array −
print("\nArray Dimensions...\n",arr.ndim)Get the number of elements of the Array −
print("\nNumber of elements in the Array...\n",arr.size)To round to nearest integer towards zero, use the numpy.fix() method in Python Numpy. It rounds an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats −
print("\nResult (rounded)...\n",np.fix(arr))Example
import numpy as np
# Create an array with float type using the array() method
arr = np.array([120.6, -120.6, 200.7, -320.1, 320.1, 500.6])
# Display the array
print("Array...\n", arr)
# Get the type of the array
print("\nOur Array type...\n", arr.dtype)
# Get the dimensions of the Array
print("\nOur Array Dimension...\n",arr.ndim)
# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)
# To round to nearest integer towards zero, use the numpy.fix() method in Python Numpy
# It rounds an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.
print("\nResult (rounded)...\n",np.fix(arr))Output
Array... [ 120.6 -120.6 200.7 -320.1 320.1 500.6] Our Array type... float64 Our Array Dimension... 1 Our Array Shape... (6,) Result (rounded)... [ 120. -120. 200. -320. 320. 500.]