• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Java help.

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

covana2244

Member
Joined
Jul 5, 2004
Location
UNK Nebraska
I need help. I have to write a java program to test a list of double numbers for whole values. Like if the number is 1.0 or 34.0 print to screen but if it is 1.3243 or 2.433 do not. How would I do this?
 
You could do something like this:

Code:
double[] x = {1.0, 3.45, 6.74, 5.0, 20.23, 1.423, 6.0, 19.0};

for(int i = 0; i < x.length; i++)
     if(Math.round(x[i]) == x[i])
          System.out.println(x[i]);
 
The only problem is that I may have to compare over a billion of numbers. I ran a for loop for a billion times and sent the counter variable in to a method that contained an equation. I need to only output the values that are whole integer values.
 
you should use the modulus operation:


Code:
public boolean testForWhole(double number) {
   return (number % 1.0 == 0);
}

This basically says that if when you divide the Double by 1 and there is no remainder (modulus), then return true. If there is a remainder, return false
 
Back