我目前正在开发温度转换器应用程序。一切正常,但我可以得到超过 5 位小数,我试图查找它并在 Google 上搜索但无法找到如何做到这一点。这是我在 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;
}
最佳答案
此处的代码暗示它正在创建一个十进制格式来完成这项工作,但是,您实际上并没有使用它!
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 位小数,但是,您使用的 Decimal 格式增加了两位。
关于java - 四舍五入到小数点后一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981607/