简体   繁体   中英

Understanding the strange output of java.util.Locale

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?

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.

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.

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