0
0
NumPydata~5 mins

np.round(), np.floor(), np.ceil() in NumPy

Choose your learning style9 modes available
Introduction

These functions help you change numbers to simpler forms. You can round numbers, or always go down or up to the nearest whole number.

When you want to round prices to two decimal places for billing.
When you need to find the largest whole number less than or equal to a value, like in age calculation.
When you want to find the smallest whole number greater than or equal to a value, like in seating arrangements.
When preparing data for charts that need whole numbers.
When cleaning data to remove decimal parts for easier analysis.
Syntax
NumPy
np.round(array, decimals=0)
np.floor(array)
np.ceil(array)

np.round() rounds to the nearest value with optional decimals.

np.floor() always rounds down to the nearest whole number.

np.ceil() always rounds up to the nearest whole number.

Examples
Rounds each number to the nearest whole number.
NumPy
np.round(np.array([1.5, 2.3, 3.7]))
Rounds each number to 2 decimal places.
NumPy
np.round(np.array([1.234, 2.345, 3.456]), decimals=2)
Rounds each number down to the nearest whole number.
NumPy
np.floor(np.array([1.7, 2.3, 3.9]))
Rounds each number up to the nearest whole number.
NumPy
np.ceil(np.array([1.2, 2.8, 3.1]))
Sample Program

This program shows how each function changes the numbers. It prints the original numbers, then the rounded, floored, and ceiled results.

NumPy
import numpy as np

numbers = np.array([1.5, 2.3, 3.7, -1.2, -2.8])

rounded = np.round(numbers)
floored = np.floor(numbers)
ceiled = np.ceil(numbers)

print('Original:', numbers)
print('Rounded:', rounded)
print('Floored:', floored)
print('Ceiled:', ceiled)
OutputSuccess
Important Notes

Negative numbers behave the same way: floor goes down (more negative), ceil goes up (less negative).

Use decimals in np.round() to control how many decimal places to keep.

Summary

np.round() changes numbers to nearest values, with optional decimals.

np.floor() always rounds numbers down to the nearest whole number.

np.ceil() always rounds numbers up to the nearest whole number.