Home For loop calculates the Celsius equivalent to Fahrenheit Temperatures Java

# For loop calculates the Celsius equivalent to Fahrenheit Temperatures Java

Marc
1#
Marc Published in 2018-02-13 22:14:30Z
 I have a problem with this program. I get no compile errors, but when I run it didn’t display the decimal point for Celsius output. Here is my code: public class TempLoops { public static void main(String args[]) { int fahrenheit = 0; System.out.println("Fahrenheit Celsius"); for ( fahrenheit = 0; fahrenheit <= 300; fahrenheit+= 20) { System.out.printf("%5d ",fahrenheit); double Celsius = (fahrenheit-32.0) * (5.0/9.0); // formula for celsius to fahrenheit conversion System.out.printf("%5d", (int)Celsius ); System.out.println(); } } }  How do I get digits behind the decimal point for Celsius output? Here is the sample output for what it suppose to look like sample out
Antoniossss
2#
 Change this System.out.printf("%5d", (int)Celsius );  to this System.out.printf("%0.2f", Celsius );  This will print centigrades with 2 decimal places. The main reason why you are getting integer output is because you are casting float(ing point number like x.abcd) into integer number, cutting of what is left as fracture part (resulting in x alone).
 Use DecimalFormat to solve your problem. Working Code : import java.text.DecimalFormat; public class TempLoops { public static void main(String args[]) { DecimalFormat f = new DecimalFormat("##.00"); // this will helps you to always keeps in two decimal places int fahrenheit = 0; System.out.println("Fahrenheit Celsius"); for ( fahrenheit = 0; fahrenheit <= 300; fahrenheit+= 20) { System.out.printf(" "+fahrenheit); double Celsius = (fahrenheit-32.0) * (5.0/9.0); // formula for celsius to fahrenheit conversion System.out.printf("\t\t"+f.format(Celsius)); System.out.println(); } } }  Kindly refer to Java Docs for more information about DecimalFormat