舍入到小数点后一位

时间:2014-07-27 13:31:57

标签: java android

我目前正在研究温度转换器应用程序。一切正常,但我可以得到超过5位小数,我试图查找并搜索谷歌,但无法找到它是如何做到的。这是我在main.java中显示文本的地方:

text = (EditText) findViewById(R.id.editText1);
result = (TextView) findViewById(R.id.tvResult);
float inputValue = Float.parseFloat(text.getText().toString());
      DecimalFormat df = new DecimalFormat("#.00");
      String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
      String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));

      if (celsiusButton.isChecked()) {
        result.setText(d);
        celsiusButton.setChecked(false);
        fahrenheitButton.setChecked(true);

      } else {
        result.setText(s);
        fahrenheitButton.setChecked(false);
        celsiusButton.setChecked(true);
      }

这是我计算的地方:

    // converts to celsius
  public static float convertFahrenheitToCelsius(float fahrenheit) {
    return ((fahrenheit - 32) * 5 / 9);

  }

  // converts to fahrenheit
  public static float convertCelsiusToFahrenheit(float celsius) {
    return ((celsius * 9) / 5) + 32;
  }

1 个答案:

答案 0 :(得分:3)

这里的代码暗示它正在创建一个十进制格式来完成工作,但是,你实际上并没有使用它!

  DecimalFormat df = new DecimalFormat("#.00");
  String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
  String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));

代码应为:

  DecimalFormat df = new DecimalFormat("#.00");
  String s = df.format(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
  String d = df.format(ConvertFahrCels.convertFahrenheitToCelsius(inputValue));

现在Java中更常见的是使用String formatting而不是十进制格式。考虑:

  String s = String.format("%.1f", ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));

最后,你的问题表明你想要1个小数位,但是,你使用的十进制格式会增加两个。