Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Round to nearest integer towards zero in Python
To round to the nearest integer towards zero in Python, use the numpy.fix() method. It performs element-wise rounding of float arrays towards zero, which means it truncates the decimal part. For positive numbers, this rounds down, and for negative numbers, it rounds up towards zero.
Syntax
numpy.fix(x, out=None)
Parameters
The function accepts the following parameters:
- x ? Array of floats to be rounded
- out ? Optional output array where results are stored
Basic Example
Let's see how np.fix() rounds different types of numbers ?
import numpy as np
# Create an array with positive and negative floats
arr = np.array([120.6, -120.6, 200.7, -320.1, 320.1, 500.6])
print("Original array:")
print(arr)
print("\nRounded towards zero:")
print(np.fix(arr))
Original array: [ 120.6 -120.6 200.7 -320.1 320.1 500.6] Rounded towards zero: [ 120. -120. 200. -320. 320. 500.]
How It Works
The numpy.fix() method truncates the fractional part, always rounding towards zero ?
import numpy as np
# Examples showing rounding behavior
examples = np.array([3.8, -3.8, 7.2, -7.2, 0.9, -0.9])
print("Original values:", examples)
print("Rounded towards zero:", np.fix(examples))
print("Regular rounding:", np.round(examples))
Original values: [ 3.8 -3.8 7.2 -7.2 0.9 -0.9] Rounded towards zero: [ 3. -3. 7. -7. 0. -0.] Regular rounding: [ 4. -4. 7. -7. 1. -1.]
Using Output Parameter
You can specify an output array to store results instead of creating a new array ?
import numpy as np
data = np.array([15.7, -22.3, 8.9])
result = np.zeros_like(data)
# Store result in existing array
np.fix(data, out=result)
print("Original:", data)
print("Result array:", result)
print("Data type:", result.dtype)
Original: [ 15.7 -22.3 8.9] Result array: [ 15. -22. 8.] Data type: float64
Comparison
| Method | Positive Numbers | Negative Numbers | Example: 3.7, -3.7 |
|---|---|---|---|
np.fix() |
Rounds down | Rounds up (toward zero) | 3.0, -3.0 |
np.floor() |
Rounds down | Rounds down | 3.0, -4.0 |
np.ceil() |
Rounds up | Rounds up | 4.0, -3.0 |
np.round() |
Nearest integer | Nearest integer | 4.0, -4.0 |
Conclusion
Use numpy.fix() when you need to truncate decimal parts towards zero. This is particularly useful for converting floats to integers while preserving the sign and avoiding rounding effects.
