Check whether double holds integer, Math.rint vs %

Viewed 109

I am trying to check whether a double holds an integer value, for example:

double d = 1.0; // true
double d = 1.2; // false
double d = 2.0; // yes
double d = 2.1; // false

I have two different approaches:

  • value % 1 == 0
  • Math.rint(value) == value

for example:

double x = 1.0;
double y = 1.2;
System.out.println(x % 1 == 0); //true
System.out.println(y % 1 == 0); //false
System.out.println(Math.rint(x) == x); //true
System.out.println(Math.rint(y) == y); //false

I am wondering about the differences between both approaches. Will they work for all integers? Is there a significant performance difference?

Are there better approaches to achieve what I am trying to achieve?

0 Answers
Related