AND4011002849 AND4011002849 - 1 year ago 94
Java Question

Parsing currency to double raising exception

I have a string which is "R$3.333,33" and I'm trying to parse it to a double value with this method:

public static BigDecimal parse(final String amount, final Locale locale) throws ParseException {
final NumberFormat format = NumberFormat.getCurrencyInstance(locale);
if (format instanceof DecimalFormat) {
((DecimalFormat) format).setParseBigDecimal(true);
return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]", ""));

But I'm getting an exception that says:

W/System.err: java.text.ParseException: Unparseable number: "3.333,33" (at offset 8)

And I'm using it like:

Ferramentas.parse(value.getText().toString(), Locale.FRANCE)

Answer Source

The only solution I found is to replace . in your regex as well:

return (BigDecimal) format.parse(amount.replaceAll("[^\\d,]",""));

I haven't been able to parse a number with a . for thousands.

  • If you keep the . it gets parsed to 3.
  • If you replace the . by ,, it gets parsed to 3.333.

If anyone has a solution for the . for thousands, I would be really interested in hearing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download