Search code examples
javaeclipse-neon

DecimalFromat Issues, mainly for 2 digits after the decimal


This is my code:

public class TemperatureConverter {
public static float convertTemp1 (float temperature,
    char convertTo) {
    return convertTo;}
    public static String convertTemp (float temperature, char convertTo) {

     if (convertTo=='F'){
     return "The temperature in Fahrenheit is " + (9*temperature/5 + 32);
    } else if(convertTo=='C') {
     return "The temperature in Celsius is " + (temperature - 32) * 5/9;
    }  else{
     return "You can enter either F or C as convertTo argument";

}
}

public static void main(String[] args) {

System.out.println("Converting 21C to Fahrenheit. " +  convertTemp(21,'F', 0));
System.out.println("Converting 70F to Celsius. " + convertTemp(70,'C', 0));
}
}

This is the output when your run it:

Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8

Converting 70F to Celsius. The temperature in Celsius is 21.11111

I have been trying again, and again to make tje 2.11111, to 2.11, only 2 digits after the decimal point. May someone help me get from this:

Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8

Converting 70F to Celsius. The temperature in Celsius is 21.11111

To this:

Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8

Converting 70F to Celsius. The temperature in Celsius is 21.11


Solution

  • You could use String.format() to specify how many digits should be shown after the decimal point:

    class Main {
      public static String convertTemp (float temperature, char convertTo) {
        if (convertTo == 'F') {
          return String.format("The temperature in Fahrenheit is %.1f", (9*temperature/5 + 32)); 
        } else if (convertTo == 'C') {
          return String.format("The temperature in Celsius is %.2f", (temperature - 32) * 5/9); 
        } else {
          return "You can enter either F or C as convertTo argument";
        }
      }
    
      public static void main(String[] args) {
        System.out.println("Converting 21C to Fahrenheit. " +  convertTemp(21,'F'));
        System.out.println("Converting 70F to Celsius. " + convertTemp(70,'C'));
      }
    }
    

    Output:

    Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8
    Converting 70F to Celsius. The temperature in Celsius is 21.11
    

    Try it here!