How to convert currency formatted String back to a BigDecimal? (using Java NumberFormat)

Viewed 6580

In my Android app I've got an EditText from which I take a number, and convert that to a BigDecimal, and from there to a local Currency formatting:

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())));

This prints out €100.000,00 like expected. I now however, want to convert this back into a BigDecimal.

Is there a way that I can convert a locally formatted currency string back to a BigDecimal?

3 Answers
    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();
    }

Currency Format: € 100.000,00

100000

In your code example you don't assign BigDecimal to something so you cant convert it back.

//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);

Hope it helps!

I've been trying to find a better solution, but this is the best I've come across so far. It relies on the fact that NumberFromat.getCurrencyInstance returns a DecimalFormat. I don't like having to cast it, but the setParseBigDecimal will cause the parse method to return a BigDecimal instead of a number. And yet another cast on parse. I'm using US locale, but it's easy to change to NL

NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
DecimalFormat)fmt).setParseBigDecimal(true);
BigDecimal amount = (BigDecimal)fmt.parse("$1,000,000.00");
System.out.println(amount.toString());
Related