Search code examples
javastringparsingformatcurrency

Parse BRL currency value String to double


I'm trying to parse the following string: "59000,00"

In Brazil, the comma is used to represent decimal places, and the point is used as a symbol to separate the thousands.

What I'm trying to do:

final String price = "59000,00";
// LocaleUtils.getLocale returns new Locale("pt", "BR")
final NumberFormat numberFormat = NumberFormat.getCurrencyInstance(LocaleUtils.getLocale());

try {
  final double d = numberFormat.parse(price).doubleValue();
  // do stuff
} catch (ParseException e) {
  // do stuff
}

However, I am getting a ParseException. Why would that be?

java.text.ParseException: Unparseable number: "59000,00" (at offset 8)


Solution

  • You can use GERMANY Locale as it uses comma as decimal separator as said here in the documentation. Like this:

    NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
    double df = nf.parse(price).doubleValue();