Round to nearest integer towards zero in Python

PythonNumpyServer Side ProgrammingProgramming

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...
",arr)

Get the datatype −

print("
Array datatype...
",arr.dtype)

Get the dimensions of the Array −

print("
Array Dimensions...
",arr.ndim)

Get the number of elements of the Array −

print("
Number of elements in the Array...
",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("
Result (rounded)...
",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...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",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("
Result (rounded)...
",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.]
raja
Updated on 28-Feb-2022 05:33:38

Advertisements