Parsing prices with Currency Symbol in Java

倖福魔咒の 提交于 2019-12-23 12:56:41

问题


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
$0.00 
$1,123.42 
1,123.42$ 
1,123.42 USD

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


回答1:


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.



来源:https://stackoverflow.com/questions/9892555/parsing-prices-with-currency-symbol-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!