如何将货币格式的String转换回BigDecimal? (使用Java NumberFormat)

时间:2013-12-05 15:21:16

标签: java android locale number-formatting

在我的Android应用程序中,我有一个EditText,我从中获取一个数字,然后将其转换为BigDecimal,并从那里转换为本地货币格式:

String s = "100000";
Locale dutch = new Locale("nl", "NL");
NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);
Log.e(this, "Currency Format: "+ numberFormatDutch.format(new BigDecimal(s.toString())));

这打印出€100.000,00与预期一样。但是,我现在想要将其转换回BigDecimal。

有没有办法可以将本地格式的货币字符串转换回BigDecimal?

2 个答案:

答案 0 :(得分:5)

    String s = "100000";
    Locale dutch = new Locale("nl", "NL");
    NumberFormat numberFormatDutch = NumberFormat.getCurrencyInstance(dutch);

    String c = numberFormatDutch.format(new BigDecimal(s.toString()));
    System.out.println("Currency Format: "+ c);
    try {
        Number  d = numberFormatDutch.parse(c);
        BigDecimal bd = new BigDecimal(d.toString());
        System.out.println(bd);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

货币格式:€100.000,00

100000

答案 1 :(得分:0)

在您的代码示例中,您没有将BigDecimal分配给某些内容,因此您无法将其转换回来。

//Assign BigDecimal
BigDeciaml x = new BigDecimal(s.toString());
//Your code line
Log.e(this, "Currency Format: "+ numberFormatDutch.format(x));
//x it's the same as before
System.out.println(x);

希望它有所帮助!