How to Round Up the Result of Integer Division

How to round up the result of integer division?

Found an elegant solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

Source: Number Conversion, Roland Backhouse, 2001

Rounding integer division (instead of truncating)

int a = 59.0f / 4.0f + 0.5f;

This only works when assigning to an int as it discards anything after the '.'

Edit:
This solution will only work in the simplest of cases. A more robust solution would be:

unsigned int round_closest(unsigned int dividend, unsigned int divisor)
{
return (dividend + (divisor / 2)) / divisor;
}

How to round up integer division and have int result in Java?

To round up an integer division you can use

import static java.lang.Math.abs;

public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

or if both numbers are positive

public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}

Divide by 3 and Round up (If need be) C#

Math.Round(num / 3);

or

Math.Ceiling(num / 3);

or

Math.Truncate(num / 3);

Round Up Integer Division

You're doing your division backwards. You must divide total lines by lines-per-page. See how the terms cancel in this way:

x pages = (y lines/1 page) / (z lines) << yeilds 1/pages (wrong!)

x pages = (z lines) / (y lines/1 page) = (z lines) * (1 page / y lines) << correct!

Also note that you need to perform double division, not integer division, then round the resulting value up since a partial page must be rounded to a full page.

Dim lines As Integer = 68 
Dim lines_per_page As Double = 65
Dim pages_used As Integer
pages_used = CType(Math.Ceiling(lines / lines_per_page), Integer)

Java: Integer division round up

You need to make your roomsOccPercentage a double first.

double roomsOccPercentage = 0.0;

and then cast either of the operands so avoid an integer division.

roomsOccPercentage = (totalRoomsOccupied * 100.0) / totalRooms;

You can either use an explicit cast like (double)totalRoomsOccupied or just make 100 as 100.0 which is a floating point number, thus making the division too, a floating point one and not an integer division.

how to always round up to the next integer

Math.Ceiling((double)list.Count() / 10);

How to round up result of dividing

In order to get the result of this operation as double you have to make at least one operand double (see https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx). Try adding 'd' to literal:

finalResult = Math.Ceiling(result = (x - y) / (z - 1d));

By doing this little trick you ensure that '1' will be treated as double, not as int, so the whole operation outcome will be a double.
Note: Unless you want to round this value up, you should change the rounding method to Math.Round().
Note 2: Make sure to prevent division by 0 by checking if(z != 0).



Related Topics



Leave a reply



Submit