Understanding the strange output of java.util.Locale

会有一股神秘感。 提交于 2019-12-24 10:25:03

问题


I had a perception that Locale is just about adding comma at proper positions at least in case of numbers. But I see a different output for what I have tried.

I tried the following,

public static void main(String[] args) {
    DecimalFormat df = null;

    df = (DecimalFormat) DecimalFormat.getInstance(Locale.CHINESE);
    System.out.println("Locale.CHINESE "+df.format(12345.45));

    df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    System.out.println("Locale.GERMAN  "+df.format(12345.45));
}

Output:

Locale.CHINESE 12,345.45
Locale.GERMAN  12.345,45

If you carefully look at the comma's, you'll see a major difference.

Now, the javadoc for java.util.Locale says

... An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture ...

I see a comma being interpreted as decimal point in another Locale, which is really a curious thing, as the value is being changed.

So, help me understand this. What exactly is Locale? Won't the drastic change in output cause major issue in code/data?


回答1:


I had a perception that Locale is just about adding comma at proper positions at least in case of numbers.

No, it affects the symbols used as well, as you've seen.

So, help me understand this. What exactly is Locale? Won't the drastic change in output cause major issue in code/data?

Only if you don't use them correctly :) Machine-to-machine communication should usually not be localized; typically if you really need to use text, it's best to use US as a reasonably invariant locale.

See DecimalFormatSymbols for more details of what is locale-specific.




回答2:


I see nothing wrong with the above. The German way of representing 12345.45 is 12.345,45
and the Chinese way of representing the same number is 12,345.45 .

So, help me understand this. What exactly is Locale? Won't the drastic change in output cause major issue in code/data?

No it won't you just need to keep track of the locale of the input and how you want it formatted.



来源:https://stackoverflow.com/questions/13569149/understanding-the-strange-output-of-java-util-locale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!