1

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)
AND4011002849
  • 1,971
  • 8
  • 38
  • 81

3 Answers3

2

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.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

Take a look at this question and answer.

Although it looks like a duplicate, the parse method works if your input is "R$ 3.333,33" (notice the space between the currency symbol and the value).

To insert a space between the currency symbol and the value, you can use a method like this:

public static String insertSpaceBetweenSymbolAndValue(String s)
{
    int index = 0;
    while (index < s.length() && !Character.isDigit(s.charAt(index)))
        index++;
    return (index != s.length()) ? s.substring(0, index) + " " + s.substring(index) : s;
}
marcelovca90
  • 2,673
  • 3
  • 27
  • 34
-2

Why not you remove 'R$ ', then parse your double?

String s = b.substring(3, b.length()); 
Double d = Double.valueOf(s);
PLe
  • 137
  • 4