Stefan Stefan - 1 year ago 65
Java Question

Parsing prices with Currency Symbol in Java

I want to parse a String that i have into a Number. This is the Code that i'm using but not working:

NumberFormat.getCurrencyInstance(Locale.GERMAN).parse("EUR 0,00");

This results in a java.text.ParseException

So i want to match the String into a number, i don't really care about the currency, but it would be nice to have.

I want the following kind of Strings matched:

EUR 0,00
EUR 1.432,89
1,123.42 USD

Sure, there are ways with RegEx, but i think it would be kind of overkill.

Answer Source

Locale.GERMAN does not seem to have a currency symbol. Locale.GERMANY has the euro symbol as its currency (not the string "EUR"). Notice that blam1 and blam3 below cause parsing exceptions, the CurrencyFormat object only likes blam2.

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.GERMANY);

System.out.println("75.13 euro: " + numberFormat.format(75.13));

try {
  System.out.println("Parsed blam1: " + numberFormat.parse("EUR 75,11"));
} catch (ParseException exception) {
  System.out.println("Parse Exception1: " + exception);

try {
  System.out.println("Parsed blam2: " + numberFormat.parse("75,12 €"));
} catch (ParseException exception) {
  System.out.println("Parse Exception2: " + exception);

try {
  System.out.println("Parsed blam3: " + numberFormat.parse("€ 75,13"));
} catch (ParseException exception) {
  System.out.println("Parse Exception3: " + exception);

I suspect that you will need to either find an open source currency parser that fits your need or write one yourself.