Results 1 to 5 of 5
Thread: Remove .0
- 01-27-2011, 10:48 PM #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");
}
}
-
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, 02:31 AM #3
-
Last edited by Fubarable; 01-28-2011 at 02:43 AM.
- 01-28-2011, 02:47 AM #5
Similar Threads
-
Remove recursion
By ama03630 in forum Advanced JavaReplies: 7Last Post: 11-15-2009, 10:24 PM -
Remove headline
By amarelv in forum New To JavaReplies: 4Last Post: 11-07-2008, 04:36 AM -
how to remove this error
By ravinder64 in forum Java ServletReplies: 1Last Post: 11-01-2008, 07:04 AM -
how to remove an old version of JDK
By tommy in forum New To JavaReplies: 2Last Post: 07-30-2007, 08:59 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks