I need to find a division of two integers and round it to next upper integer
e.g x=7/y=5 = 2; here x and y always greater than 0
This is my current code
int roundValue = x % y > 0? x / y + 1: x / y;
Is there any better way to do this?
ceil() The Math. ceil() function always rounds a number up to the next largest integer. Note: Math.
Rounding to the Nearest IntegerIf 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() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
Math. round() - rounds to the nearest integer (if the fraction is 0.5 or greater - rounds up) Math. floor() - rounds down.
You could use Math.Ceiling
... but that will require converting to/from double
values.
Another alternative is to use Math.DivRem
to do both parts at the same time.
public static int DivideRoundingUp(int x, int y) { // TODO: Define behaviour for negative numbers int remainder; int quotient = Math.DivRem(x, y, out remainder); return remainder == 0 ? quotient : quotient + 1; }
Try (int)Math.Ceiling(((double)x) / y)
All solutions looks too hard. For upper value of x/y, use this one
( x + y - 1 ) / y
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