如何将双精度更改为字符串

How to change a double to a string

我有一个在 EditText 中显示字符串的应用程序,该字符串是在两个不同的 EditText 中对另外两个用户类型进行双重操作的结果。 问题是我希望操作的结果显示在第三个 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 中是 运行,但在真实设备中却不正确。有什么想法吗?

double BMI_trimmed = Double.parseDouble(df.format(BMI));
String yourResult = String.valueOf(BMI_trimmed);  

编码愉快

您已经根据需要四舍五入并从格式化程序中获取字符串形式的值。不要试图解析它,只是显示它。

BMIResult.setText(df.format(BMI));

问题可能出在您的 phone 区域设置上。一些 phone 使用 .作为分隔符,有些使用 , 作为分隔符。尝试将所有“,”替换为“。”在从 String 解析为 Double 之前。

也尝试使用这个答案: