用Java中的货币符号解析价格 [英] Parsing prices with Currency Symbol in Java

查看:261
本文介绍了用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");

这将导致java.text.ParseException

This results in a java.text.ParseException

所以我想将String匹配为一个数字,我不太在乎货币,但是拥有它会很好.

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

当然,RegEx有很多方法,但是我认为这有点过分.

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

推荐答案

Locale.GERMAN似乎没有货币符号. Locale.GERMANY使用欧元符号作为其货币(而不是字符串"EUR").请注意,下面的blam1和blam3会导致解析异常,CurrencyFormat对象仅喜欢blam2.

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.

这篇关于用Java中的货币符号解析价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆