[英]Rounding to one decimal place
I im currently working on a temprature converter app. 我目前正在研究温度转换器应用程序。 Everything works but I can get over 5 decimals and I have tried to look it up and search on Google but can't find out how do it. 一切正常,但我可以得到超过5位小数,我试图查找并搜索谷歌,但无法找到它是如何做到的。 Here is where I display the text in the main.java: 这是我在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);
}
And here is where I calculate it: 这是我计算的地方:
// 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;
}
Your code here implies it is creating a decimal format to do the work, but, you don't actually use it! 这里的代码暗示它正在创建一个十进制格式来完成工作,但是,你实际上并没有使用它!
DecimalFormat df = new DecimalFormat("#.00"); String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue))); String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));
The code should be: 代码应该是:
DecimalFormat df = new DecimalFormat("#.00");
String s = df.format(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
String d = df.format(ConvertFahrCels.convertFahrenheitToCelsius(inputValue));
It is more common in Java now to use String formatting instead of decimal format. 现在在Java中更常见的是使用字符串格式而不是十进制格式。 Consider: 考虑:
String s = String.format("%.1f", ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
Finally, your question indicates you want 1 decimal place, but, the Decimal format you use adds two. 最后,您的问题表明您想要1位小数,但是,您使用的十进制格式会增加两位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.