Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a positive float up the next integer?

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.

like image 842
srayner Avatar asked Sep 22 '14 11:09

srayner


People also ask

How do you round up to the next integer?

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.

How do you round a float to an integer in Python?

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.

How do you round to the next integer in Python?

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.

Does float round up or down?

Float number always round up.


1 Answers

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()

like image 189
David Heffernan Avatar answered Sep 21 '22 18:09

David Heffernan