Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

primitive

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?

like image 429
Shaun Avatar asked Oct 15 '09 21:10

Shaun


People also ask

How do you check if a variable is an integer in Java?

To check if a String contains digit character which represent an integer, you can use Integer. parseInt() . To check if a double contains a value which can be an integer, you can use Math. floor() or Math.

How do you check if a number is not an integer in Java?

double a = 1.00 if(floor(a) == a) { // a is an integer } else { //a is not an integer. }

How do you know if a number is a double or integer?

This checks if the rounded-down value of the double is the same as the double. Your variable could have an int or double value and Math. floor(variable) always has an int value, so if your variable is equal to Math. floor(variable) then it must have an int value.


3 Answers

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)

like image 77
dfa Avatar answered Oct 12 '22 03:10

dfa


I am not sure if it is any faster, but you could cast your double to an int and test for equality:

double d = 123.456;
boolean dIsAnInteger = (d == (int)d);
like image 25
akf Avatar answered Oct 12 '22 03:10

akf


Warning: would you consider 0.9999999999999999 an integer? Probably not. But watch this:

double val = 0;
for(int i=0;i<10;i++)
    System.out.println(val+=0.1);

This prints out:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Which is problematic because at the end of the program val contains something that you think should be integer but is not.

So I'd make my method a bit slower (but more correct) by integrating a delta like JUnit does:

private static boolean isInt(double x, double delta) {
    double ceil = Math.ceil(x);
    return x-delta<ceil && x+delta>ceil;
}

and of course provide the same method with a sensible default:

private static boolean isInt(double x) {
    return isInt(x, 0.000000001);
}

Now isInt(val) finally returns true.

like image 34
cherouvim Avatar answered Oct 12 '22 02:10

cherouvim