【发布时间】:2020-04-12 14:10:13
【问题描述】:
我有一个应用程序,它在 EditText 中显示一个字符串,这个字符串是用户在两个不同的 EditTexts 中键入的另外两个 double 操作的结果。 问题是我希望操作的结果显示在第三个 EditText 中,但它必须是一个字符串。因此我通过 toString 方法更改结果。
问题从这里开始,我希望作为字符串的双精度只有一位小数。为此,我使用了 DecimalFormat 并创建了 df 格式“#.#”。然后我将最后一个 EditText 中显示的文本更改为只有一位小数的新双变量(显然将其更改为字符串)。
DecimalFormat df = new DecimalFormat("#.#");
double BMI_trimmed = Double.parseDouble(df.format(BMI));
final EditText BMIResult = (EditText)findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI_trimmed));
这里我把 myButtonListenerMethod 的所有代码留给你:
public void myButtonListenerMethod(){
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final EditText heighText = (EditText)findViewById(R.id.heightInput);
String heighStr = heighText.getText().toString();
double height = Double.parseDouble(heighStr);
final EditText weighText = (EditText)findViewById(R.id.weightInput);
String weighStr = weighText.getText().toString();
double weight = Double.parseDouble(weighStr);
double BMI = (weight)/(height*height);
DecimalFormat df = new DecimalFormat("#.#");
double BMI_trimmed = Double.parseDouble(df.format(BMI));
final EditText BMIResult = (EditText)findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI_trimmed));
}
});
}
这个应用程序在 AVD 上完美运行,我已经运行了三个。但是当我在真实设备上运行它并单击启动 myButtonListenerMethod 的按钮时,它突然停止工作并关闭。终端给出以下错误信息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bmicalculator, PID: 19058
java.lang.NumberFormatException: For input string: "24,2"
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
如果有人知道问题出在哪里,请告诉我,我会试试。老实说,我不明白为什么它在 AVD 中运行,但在真实设备中却不能正常运行。有什么想法吗?
【问题讨论】:
-
嗯,根据设备的区域设置,输入“24,2”可能不是有效数字。您能帮我们验证一下语言环境吗?
-
某些语言环境使用逗号作为小数分隔符,您的设备可能正在使用这样一种语言环境。请检查此 SO question.
标签: java android numberformatexception decimalformat