java - 使用 double 仅显示小数点后两位数

标签 java android double

我使用:

priceTextView.setText(String.format("%.2f",price));

价格翻倍。它有效,但是当我必须从 TextView 检索值并将其转换为 double 时,出现以下错误:

java.lang.NumberFormatException: Invalid double: "1,2"

是否有另一种方法可以做同样的事情并避免错误?

完整代码如下:

Double prezzoDouble = Double.parseDouble(this.prezzo);
prezzoTextView.setText(String.format("%.2f", prezzoDouble));

quantitaSceltaEditText.addTextChangedListener(new TextWatcher() {

    String prezzoUnitario=prezzo;

    public void afterTextChanged(Editable s) {

        int quantitaSceltaInt = Integer.parseInt(quantitaSceltaEditText.getText().toString());

        if(quantitaSceltaInt>=1) {
            String prezzoTotale = String.valueOf(String.format ("%.2f", (calcoloPrezzoTotale())));
            prezzoTextView.setText(prezzoTotale);
        }
        else
        {
            prezzoTextView.setText(prezzoUnitario);
        }
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    private double calcoloPrezzoTotale()
    {
        double prezzoNum=Double.parseDouble(prezzoTextView.getText().toString()); ///////////
        double prezzoTotale=0;

        int quantitaSceltaNum = Integer.parseInt(quantitaSceltaEditText.getText().toString());

        prezzoTotale = prezzoNum * quantitaSceltaNum;

        return prezzoTotale;
    }
});

最佳答案

看起来像行中的双重赋值

prezzoTotale = String.valueOf(String.format ("%.2f", (calcoloPrezzoTotale())));

由于区域设置,包含逗号(,,即 1,2)。因此,请注意使用相同的语言环境进行解析。

NumberFormat帮助你:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

查看您的代码,它也可能是 Locale.ITALY ;) 检查完整的 Locale 列表 here .

p.s.:String.format() 根据 documentation 使用 Locale.getDefault(); .使用 logcat 检查它的值,如果您不确定系统设置或使用替代方法 public static String format(Locale l, String format, Object... args) 允许您指定语言环境。

关于java - 使用 double 仅显示小数点后两位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29637005/

相关文章:

java - 我可以使用 isAssignableFrom 来检查 Java 中 C1 是 C2 的子类型吗?

java - java有没有好的dataflow并发库

android - 如何在 Android Studio 中导入 dropbox Chooser SDK?

android - 如何使用 android 中的下载管理器将下载的图像存储在内部存储中

c++ - GCC C/C++ 双重行为

java - 如果我没有与之共享,JRuby 中的 Ruby 脚本可以使用我的 Java 类吗?

java - 该方法应该返回一个排序数组,但为什么我会收到 NullPointerException?

android - ParseObject.remove 在 Back4App 中不起作用

java - 我可以从两个整数中设置一个 double 吗?

c++ - atoi 与整数和 double