-1

Can I make an if statement in Java like the one below, that ensures that a number is round?

if(some number int)
Anders
  • 8,307
  • 9
  • 56
  • 88

3 Answers3

3

Yes

System.out.println(6.0 % 1 == 0);

prints

true

while

System.out.println(6.1 % 1 == 0);

prints

false

As the JLS specifies for the remainder operation for floating point numbers :

In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r = n - (d · q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

Therefore, if n is the number you wish to test and d is 1, the remainder r is r = n - q for some integer q. Therefore, if the remainder r is 0, n = q for some integer q, so your tested number n is an integer.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

I guess you want to check if a number is an int:

public boolean isObjectInteger(Object o) { return o instanceof Integer; }

Should do the job.

Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
0

Alternatively, using Math.rint:

if(x == Math.rint(x))
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118