Java I18n 简明教程

Java Internationalization - Locale Specific DecimalFormat

默认情况下,DecimalFormat 对象使用 JVM 的区域设置。我们可以在创建 DecimalFormat 对象时使用 NumberFormat 类更改默认区域设置。在以下示例中,我们将针对两个不同区域设置使用相同的模式,您可以在输出中发现差异。

By default, DecimalFormat object is using the JVM’s locale. We can change the default locale while creating the DecimalFormat object using NumberFormat class. In the example below, we’ll use same pattern for two different locale and you can spot the difference in the output.

Example

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class I18NTester {
   public static void main(String[] args) {
      String pattern = "###.##";
      double number = 123.45;

      Locale enlocale  = new Locale("en", "US");
      Locale dalocale  = new Locale("da", "DK");

      DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(enlocale);
      decimalFormat.applyPattern(pattern);

      System.out.println(decimalFormat.format(number));

      decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(dalocale);
      decimalFormat.applyPattern(pattern);

      System.out.println(decimalFormat.format(number));
   }
}

Output

它将打印以下结果。

It will print the following result.

123.45
123,45