开发者

Parse Japanese currency String with java.text.NumberFormat

开发者 https://www.devze.com 2023-03-03 16:10 出处:网络
I face problems parsing a Japanese currency string in Java. It seems that the Yen symbol is not matching what java think it should be. Here is my code:

I face problems parsing a Japanese currency string in Java. It seems that the Yen symbol is not matching what java think it should be. Here is my code:

NumberFormat f = NumberFormat.getCurrencyInstance(Locale.JAPAN);
开发者_Python百科String s = "¥200";
Number n = f.parse(s);

This will throw an exception:

Exception in thread "main" java.text.ParseException: Unparseable number: "¥200"
at java.text.NumberFormat.parse(NumberFormat.java:333)

Seems that java uses a different symbol for Yen ("\uFFE5")

Can someone help with that? Thanks


Try change the character "¥"(0xC2A5) to "¥"(0xEFBFA5).
"¥"(0xC2A5) is special character in Japanese locale.


NumberFormat f = NumberFormat.getCurrencyInstance(Locale.UK);
        String s = "£200";
        Number n = f.parse(s);

AND

    NumberFormat f = NumberFormat.getCurrencyInstance(Locale.US);
    String s = "$200";
    Number n = f.parse(s);

Will have the same affect. NumberFormat works on numbers, not on a string character i.e. you need to remove the currency symbol if you are allowing NumberFormat to parse integers only (the default). What you can do is this:

NumberFormat f = NumberFormat.getCurrencyInstance(Locale.JAPAN);
String s = "¥200";
f.setParseIntegerOnly(false);
Number n = f.parse(s);

This will allow the Yen character through. Try it with $ and it fails. But change the local to US and the $ is allowed and the Yen is not.

0

精彩评论

暂无评论...
验证码 换一张
取 消