我想将我拥有的字符串解析为数字。这是我正在使用但无法正常工作的代码:
NumberFormat.getCurrencyInstance(Locale.GERMAN).parse("EUR 0,00");
这会导致 java.text.ParseException
所以我想将字符串匹配成一个数字,我不太关心货币,但它会很好。
我想要匹配以下类型的字符串:
EUR 0,00
EUR 1.432,89
$0.00
$1,123.42
1,123.42$
1,123.42 USD
当然,RegEx 有很多方法,但我认为这有点矫枉过正。
最佳答案
Locale.GERMAN 似乎没有货币符号。 Locale.GERMANY 将欧元符号作为其货币(不是字符串“EUR”)。请注意下面的 blam1 和 blam3 会导致解析异常,CurrencyFormat 对象只喜欢 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);
}
我怀疑您需要找到适合您需要的开源货币解析器或自己编写一个。
关于java - 在 Java 中使用货币符号解析价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9892555/