Search code examples
javamathtypesformatting

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?


Solution

  • Ceiling

    Normal integer division rounds to zero, truncating any fraction.

    Instead, what you want is to round toward positive infinity, known as the ceiling.

    Math.ceilDiv

    In Java 18+, use Math.ceilDiv. Pass your two int values, dividend and divisor. Returns an int.

    int x = 15 / 8 ;                 // 1
    int y = Math.ceilDiv ( 15 , 8 )  // 2
    

    Math.ceil

    In earlier Java, use Math.ceil(), casting 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

    Syntax:

    (int) Math.ceil( (double) dividend / divisor );
    
    int x = 15 / 8 ;                                  // 1
    int y = ( int ) Math.ceil ( ( double ) 15 / 8 );  // 2