DecimalFromat 问题,主要针对小数点后2位

DecimalFromat Issues, mainly for 2 digits after the decimal

这是我的代码:

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));
}
}

这是当您 运行 时的输出:

将 21C 转换为华氏度。华氏温度为 69.8

正在将 70F 换算成摄氏度。摄氏温度为 21.11111

我一直在尝试,一次又一次,使 tje 2.11111 到 2.11,小数点后只有 2 位数字。有人可以帮我解决这个问题吗:

将 21C 转换为华氏度。华氏温度为 69.8

正在将 70F 换算成摄氏度。摄氏温度为 21.11111

为此:

将 21C 转换为华氏度。华氏温度为 69.8

正在将 70F 换算成摄氏度。摄氏温度为 21.11

我认为这应该可行:

    float temp = .....F;

    DecimalFormat df = new DecimalFormat("#,##0.0#");
    String formatedString = df.format(temp);

    System.out.println("temp: " + formatedString);

输入:69.888888 > 输出:"temp: 69.89"

输入:69.8 > 输出:"temp: 69.8"

在您的示例中,您用 69.8 省略了尾随零,如果您想要更多或更少的尾随零,只需将 # 更改为 0,反之亦然。

您想使用 String.format()。例如:

  public class T {
  public static void main(String[] args) {
    System.out.println(String.format("%.2f", 10.12312));
  }
}

您可以使用String.format()指定小数点后应显示多少位数字:

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'));
  }
}

输出:

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

试一试here!