简体   繁体   中英

Parse Japanese currency String with java.text.NumberFormat

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);
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 ("\¥")

Can someone help with that? Thanks

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 ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM