Search code examples
javaprimitive

Fastest most efficient way to determine decimal value is integer in Java


Given a double variable named sizeValue and sizeValue contains something other than 0, what is the most efficient way to determine that sizeValue contains a value that is an integer?

Currently i'm using

sizeValue % 1 == 0

any other faster ways?


Solution

  • give a try to Math.ceil:

    private static boolean isInt(double x) {
         return x == Math.ceil(x);
    }
    

    EDIT

    I've done some benchmarks with the following methods:

    private static boolean isInt1(double x) {
        return x == (int) x;
    }
    
    private static boolean isInt2(double x) {
        return x == Math.ceil(x);
    }
    
    private static boolean isInt3(double x) {
        return x % 1 == 0;
    } 
    

    isInt1 is the faster of them (on a sunjre 1.6)