Interessante piccolo problema. È un po 'complicato, dal momento che i numeri reali, non sempre rappresentano interi esatti, anche se sono pensati, quindi è importante consentire una tolleranza.
Per esempio la tolleranza potrebbe essere 1E-6, nei test di unità, ho mantenuto una tolleranza piuttosto grossolana per avere numeri più corti.
Nessuna delle risposte che posso leggere ora lavora in questo modo, ecco la mia soluzione:
public boolean isInteger(double n, double tolerance) {
double absN = Math.abs(n);
return Math.abs(absN - Math.round(absN)) <= tolerance;
}
E il test di unità, per assicurarsi che funzioni:
@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));
}
questo Double.MIN_VALUE% 1 == 0 dà false –
@Evgeniy Dopotutto, 'Double.MIN_VALUE' non è completo. –
+1 sei sodo –