如何将Unicode值转换为字符? [英] How to convert Unicode value to character?

查看:144
本文介绍了如何将Unicode值转换为字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从服务器接收此值(20B9)作为货币,这是印度卢比(₹)的相应符号.如何从utf值在文本视图中显示货币符号??

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

下面是我从服务器收到的JSONObject.

Below is the JSONObject i receive from server.

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

我正在使用belove函数来格式化产品成本

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);
}

但是我得到\ u20B9,因为输出不是₹

But I am getting \u20B9 as the output not ₹

推荐答案

20B9是Unicode点值. IE. U + 20B9.它不是经过编码的,也不是UTF-8.

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

尝试currencySymbol.getBytes("UTF-8")是毫无意义的,因为您的字符串已经从字节中解码出来了-您将得到的只是十六进制字符串的ASCII字节,因此您将获得响应.

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.

相反,您需要:

  1. 将十六进制转换为代表Unicode代码点的整数
  2. 在给定的Unicode代码点获取字符

示例:

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

这篇关于如何将Unicode值转换为字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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