Interesting little problem. It is a bit tricky, since real numbers, not always represent exact integers, even if they are meant to, so it's important to allow a tolerance.
For instance tolerance could be 1E-6, in the unit tests, I kept a rather coarse tolerance to have shorter numbers.
None of the answers that I can read now works in this way, so here is my solution:
public boolean isInteger(double n, double tolerance) {
double absN = Math.abs(n);
return Math.abs(absN - Math.round(absN)) <= tolerance;
}
And the unit test, to make sure it works:
@Test
public void checkIsInteger() {
final double TOLERANCE = 1E-2;
assertThat(solver.isInteger(1, TOLERANCE), is(true));
assertThat(solver.isInteger(0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(1.1, TOLERANCE), is(false));
assertThat(solver.isInteger(-1, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.999, TOLERANCE), is(true));
assertThat(solver.isInteger(-0.9, TOLERANCE), is(false));
assertThat(solver.isInteger(-1.001, TOLERANCE), is(true));
assertThat(solver.isInteger(-1.1, TOLERANCE), is(false));
}