0

I am using NumberFormat.getCurrencyInstance(Locale.CHINA) to get a Chinese currency symbol, but it always displays a "?" instead of the symbol of the Chinese yuan.

For example, here is my code:

NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.CHINA);
String result = currency.format(1234567.891);
System.out.println(result);

Then I run the code, and it displays: ?1,234,567.891

I found others asked similar questions before but most of the advice is to use other codes instead. I just want to know why this happened to me because my friends use the same code and their computers display the correct form. Could it be a plug-in problem? What do I need to do? I am a beginner in java, thank you all for your help.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • 3
    This is down to how your terminal displays unicode characters. – Andy Turner Aug 02 '22 at 09:45
  • 1
    Works on my machine, output: `¥1,234,567.89`… Does your console support the symbol? – deHaar Aug 02 '22 at 09:45
  • 2
    Your application likely works fine, but the application that displays the output (some terminal? cmd.exe?) cannot display that thing correctly and instead prints a `?`. – f1sh Aug 02 '22 at 09:47
  • 2
    System.out uses a non-Unicode encoding or font on your PC that cannot handle the yuan. Try printing `"¥"` directly. – Joop Eggen Aug 02 '22 at 09:50
  • 1
    1) where is that output being done? command line? which system? ... 2) Windows and DOS-box: try `chcp 65001` before running the program (see this question [Change default code page of Windows console to UTF-8](https://superuser.com/q/269818) or my preference: [Change CodePage in CMD permanently?](https://stackoverflow.com/a/56091362/16320675)); for IDE console: depends on the IDE settings – user16320675 Aug 02 '22 at 10:04

1 Answers1

2

Use DecimalFormat instead of NumberFormat. This has currency support and will display the correct symbol for you.

System.out.println(DecimalFormat.getCurrencyInstance(Locale.CHINA).format(1234567.891));
Alexander L. Hayes
  • 3,892
  • 4
  • 13
  • 34
  • This works, thanks. But can someone explain why? The getCurrencyInstance() method returns a NumberFormat and not a DecimalFormat. And when you store the returning NumberFormat in a variable for later use, it won't work again. It just works when calling the format() method directly as you described. – Slevin Jun 02 '23 at 03:40