Java: How to check if a double has a decimal potion?

statik213

Golden Member
Oct 31, 2004
1,654
0
0
I'm doing this right now:

double d;

if(d > (long) d)
// has a decimal potion
else
// is an integer

is there a better a way?
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
I would have done this:

double d;
if((int)d == d){
//stuff
}
else{
//other stuff
}

Your code doesn't work with negative numbers.
 

Argo

Lifer
Apr 8, 2000
10,045
0
0
You can use modulus operator (%) with doubles as well.

double d;
if (d % 1.0 > 0)
// We have decimal part.
 

statik213

Golden Member
Oct 31, 2004
1,654
0
0
Originally posted by: notfred
I would have done this:

double d;
if((int)d == d){
//stuff
}
else{
//other stuff
}

Your code doesn't work with negative numbers.

ok, didnt think of that