Android temperature conversion force close
I have an app which has a section that needs to convert the temperature from Celsius to Fahrenheit, but for some re开发者_运维技巧ason on only a couple phone models (like the htc desire and Sony Ericsson X10) it crashes at this part, but I have no idea why. can anyone help?
double cel = x/10;
finalTFF = 9.0f/5.0f * cel + 32.0;
DecimalFormat twoDForm = new DecimalFormat("##.0");
double NfinalTFF = Double.valueOf(twoDForm.format(finalTFF));
return twoDForm.format(NfinalTFF);
Why so difficult? As I see, you want to convert a double into a string, so:
public static String celsiusToFahrenheit(double celsius) throws Exception {
double result = ((celsius * 9) / 5) + 32;
return String.format("%.2f", result);
}
That should work :)
You are probably getting NumberFormatException when calling
double NfinalTFF = Double.valueOf(twoDForm.format(finalTFF));
Depending on the language settings on the phone decimal separator is "." or ",". When calling valueOf, only "." is accepted. Keenora is correct that the code can be simplyfied, but to avoid the crash in your code you can add a replace statement like so:
double NfinalTFF = Double.valueOf(twoDForm.format(finalTFF).replace(",", "."));
精彩评论