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

I just wrote a tiny method to count the number of pages for cell phone SMS. I didn't have the option to round up using Math.ceil, and honestly it seems to be very ugly.

Here is my code:

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
   String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";

   System.out.printf("COunt is %d ",(int)messagePageCount(message));



}

public static double messagePageCount(String message){
    if(message.trim().isEmpty() || message.trim().length() == 0){
        return 0;
    } else{
        if(message.length() <= 160){
            return 1;
        } else {
            return Math.ceil((double)message.length()/153);
        }
    }
}

I don't really like this piece of code and I'm looking for a more elegant way of doing this. With this, I'm expecting 3 and not 3.0000000. Any ideas?

This question is related to java math types formatting

The answer is


(message.length() + 152) / 153

This will give a "rounded up" integer.


Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.


Use Math.ceil() and cast the result to int:

  • This is still faster than to avoid doubles by using abs().
  • The result is correct when working with negatives, because -0.999 will be rounded UP to 0

Example:

(int) Math.ceil((double)divident / divisor);

long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();

Google's Guava library handles this in the IntMath class:

IntMath.divide(numerator, divisor, RoundingMode.CEILING);

Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.


this might be helpfull,, Subtract the remainder to the legnth and make it a divisible number and then divide it with 153

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and 
                                  //then divide by 153 

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b


Expanding on Peter's solution, this is what I've found works for me to always round 'towards positive infinity':

public static long divideAndRoundUp(long num, long divisor) {
    if (num == 0 || divisor == 0) { return 0; }

    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);

    if (sign > 0) {
        return (num + divisor - 1) / divisor;
    }
    else {
        return (num / divisor);
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r