1. Member
Join Date
Jan 2011
Posts
1
Rep Power
0

## 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");

}
}

2. 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.

3. 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.

4. 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.
Last edited by Fubarable; 01-28-2011 at 03:43 AM.

5. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•