I need to round a positive float upwards to the nearest integer.
examples;
1.0 rounds up to 1
2.1 rounds up to 3
3.5 rounds up to 4
4.9 rounds up to 5
i.e. always round up.
Rounding to the Nearest Integer If the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.
Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.
Python's Built-in round() FunctionPython has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.
Float number always round up.
Use the Ceil
function from the Math
unit. From the documentation:
Rounds variables up toward positive infinity.
Call Ceil (as in ceiling) to obtain the lowest integer greater than or equal to X. The absolute value of X must be less than MaxInt. For example:
- Ceil(-2.8) = -2
- Ceil(2.8) = 3
- Ceil(-1.0) = -1
I cannot tell whether or not the behaviour of Ceil
meets your expectations for negative input values, because you did not specify what to do there. However, if Ceil
does not meet your expectations, it is easy enough to write a function to meet your needs, by combining Abs()
and Ceil()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With