# Remove .0

• 01-27-2011, 11:48 PM
maple_leafs182
Remove .0
Hey, I'm new to Java and I have an assignment where I have to convert a temperature in Celsius to Fahrenheit, easy enough. The thing is I need to find a way to remove the .0 if it is a whole number
I tried the following way but it doesn't work, 32 will print out as 32.0.

I got it to work using 4 if statements but I want to find a shorter way to do it.

import java.util.Scanner;

public class Convert
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);

double celsius;
double fahrenheit;

//Get user input
System.out.print("Enter a temperature in celsius ");
celsius = keyboard.nextDouble();

//convert to fahrenheit
fahrenheit = (celsius*9)/5+32;

//check for decimal 0
double temp1 = celsius;
temp1 *= 10;
temp1 %= 10;
if (temp1 == 0)
celsius = ((int)celsius);

double temp2 = fahrenheit;
temp2 *= 10;
temp2 %= 10;
if (temp2 == 0)
fahrenheit = ((int)fahrenheit);
else
fahrenheit = fahrenheit;

System.out.println("\n" + celsius + " degrees Celsius is equivilant to " + fahrenheit + " degrees Fahrenheit");

}
}
• 01-28-2011, 12:00 AM
Fubarable
Your number will always be a double, and the idea of exact "whole numbers" doesn't really exist for doubles except perhaps multiples of 2. Myself, I'd format my result to the desired level using a DecimalFormat object or String.format(...), either would work.
• 01-28-2011, 03:31 AM
Zack
Quote:

Originally Posted by Fubarable
Your number will always be a double, and the idea of exact "whole numbers" doesn't really exist for doubles except perhaps multiples of 2.

How's that? I mean, I know a lot of doubles end up being stuff like 3.0000000000000000000183 (made that up, please don't count the decimal places :D), but that's still technically whole for most purposes.
• 01-28-2011, 03:40 AM
Fubarable
Quote:

Originally Posted by Zack
How's that? I mean, I know a lot of doubles end up being stuff like 3.0000000000000000000183 (made that up, please don't count the decimal places :D), but that's still technically whole for most purposes.

Yep, it's practically a whole number, but not exactly or precisely a whole number. If you introduce a ± delta, then all will be fine.
• 01-28-2011, 03:47 AM
Zack
Quote:

Originally Posted by Fubarable
Yep, it's practically a whole number, but not exactly or precisely a whole number. If you introduce a ± delta, then all will be fine.

Ah, good. That's what I figured.