Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math Round to always upper integer

Tags:

c#

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?

like image 313
Damith Avatar asked Aug 01 '11 10:08

Damith


People also ask

Does Math ceil always round up?

ceil() The Math. ceil() function always rounds a number up to the next largest integer. Note: Math.

How do you round an integer?

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.

How do you round to upper value in JavaScript?

round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

What is the difference between Math floor and Math round?

Math. round() - rounds to the nearest integer (if the fraction is 0.5 or greater - rounds up) Math. floor() - rounds down.


3 Answers

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; } 
like image 150
Jon Skeet Avatar answered Nov 02 '22 11:11

Jon Skeet


Try (int)Math.Ceiling(((double)x) / y)

like image 29
Evren Kuzucuoglu Avatar answered Nov 02 '22 12:11

Evren Kuzucuoglu


All solutions looks too hard. For upper value of x/y, use this one

( x + y - 1 ) / y
like image 31
Milan Matějka Avatar answered Nov 02 '22 12:11

Milan Matějka