How to convert Unicode value to character?

2019-05-26 13:21发布

问题:

I am receiving this value (20B9) as currency from the server which is the corresponding sign for Indian Rupee (₹). How to display the currency symbol in a textview from the utf value.?

Below is the JSONObject i receive from server.

"currency": {
    "name": "Indian rupee",
    "isoCode": "INR",
    "symbol": "20B9",
    "decimalDigits": 2
  }

And I am using the belove function to format the cost of a product

  public static String formatAmount(Currency currency, double amount) {
    String currencySymbol =  "\\u"+currency.getSymbol();
    DecimalFormat df = new DecimalFormat("#");
    df.setMaximumFractionDigits(0);
    byte[] utf8 = new byte[0];
    try {
        utf8 = currencySymbol.getBytes("UTF-8");
        currencySymbol = new String(utf8, "UTF-8");
        System.out.println(currencySymbol);
    } catch (UnsupportedEncodingException e) {
        currencySymbol = currency.getIsoCode();
    }
    return currencySymbol + df.format(amount);
}

But I am getting \u20B9 as the output not ₹

回答1:

20B9 is a Unicode point value. I.e. U+20B9. It's not encoded and not UTF-8.

It's pointless trying to currencySymbol.getBytes("UTF-8") as your string has already been decoded from bytes - all you will get is the ASCII bytes of the string of the hex, hence the response you're getting.

Instead, you need to:

  1. Convert the hex to an integer, which represents the Unicode code point
  2. Get the char at the given Unicode code point

Example:

 int codepoint = Integer.parseInt(currency.getSymbol(), 16);
 char[] currencySymbol =Character.toChars(codepoint);


标签: android utf-8