To round a number up to the nearest integer in Python, use the math.ceil()
function.
The math.ceil()
function is part of the math
module, a standard library in Python that provides access to mathematical functions. This function takes a number as input and returns the smallest integer greater than or equal to that number. In other words, it rounds the number "up" to the nearest whole number.
Here's how to use it:
import math
number = 3.14
rounded_up = math.ceil(number)
print(rounded_up) # Output: 4
number = 7.0
rounded_up = math.ceil(number)
print(rounded_up) # Output: 7
number = -2.5
rounded_up = math.ceil(number)
print(rounded_up) # Output: -2
Explanation:
-
import math
: This line imports themath
module, giving you access to its functions, includingceil()
. -
math.ceil(number)
: This is where the rounding happens. Theceil()
function takes thenumber
you want to round as an argument. -
Return Value: The
ceil()
function returns the smallest integer greater than or equal to the input number. This integer will be a float value.
Key Takeaways:
math.ceil()
always rounds up, even if the decimal part of the number is very small.- The function works with both positive and negative numbers.
- The returned value is a float. If you require an integer, you can cast the result to an integer using
int(math.ceil(number))
.
import math
number = 5.99
rounded_up_int = int(math.ceil(number))
print(rounded_up_int) # Output: 6