我尝试为美国国家/地区定制数字格式。到目前为止,它工作正常。
// Not something I want.
NumberFormat numberFormat0 = NumberFormat.getNumberInstance(Locale.US);
System.out.println("US = " + numberFormat0.format(1234.0) + " (I wish to have 1,234.00)");
System.out.println("US = " + numberFormat0.format(1234.567) + " (I wish to have 1,234.567)");
System.out.println("US = " + numberFormat0.format(1234.5678) + " (I wish to have 1,234.568)\n");
// Yes. Something I want :)
NumberFormat goodNumberFormat = new DecimalFormat("#,##0.00#");
System.out.println("US = " + goodNumberFormat.format(1234.0) + " (I wish to have 1,234.00)");
System.out.println("US = " + goodNumberFormat.format(1234.567) + " (I wish to have 1,234.567)");
System.out.println("US = " + goodNumberFormat.format(1234.5678) + " (I wish to have 1,234.568)\n");
这是输出。
US = 1,234 (I wish to have 1,234.00)
US = 1,234.567 (I wish to have 1,234.567)
US = 1,234.568 (I wish to have 1,234.568)
US = 1,234.00 (I wish to have 1,234.00)
US = 1,234.567 (I wish to have 1,234.567)
US = 1,234.568 (I wish to have 1,234.568)
但是,同样的事情在法国并不行得通。因为他们使用
,
表示.
,使用“空格”表示,
。我写下面的代码。
// Not something I want.
NumberFormat numberFormat1 = NumberFormat.getNumberInstance(Locale.FRANCE);
System.out.println("FRANCE = " + numberFormat1.format(1234.0) + " (I wish to have 1 234,00)");
System.out.println("FRANCE = " + numberFormat1.format(1234.567) + " (I wish to have 1 234,567)");
System.out.println("FRANCE = " + numberFormat1.format(1234.5678) + " (I wish to have 1 234,567)\n");
// Exception in thread "main" java.lang.IllegalArgumentException: Malformed pattern "# ##0,00#"
NumberFormat goodNumberFormat1 = new DecimalFormat("# ##0,00#");
System.out.println("FRANCE = " + goodNumberFormat1.format(1234.0) + " (I wish to have 1 234,00)");
System.out.println("FRANCE = " + goodNumberFormat1.format(1234.567) + " (I wish to have 1 234,567)");
System.out.println("FRANCE = " + goodNumberFormat1.format(1234.5678) + " (I wish to have 1 234,567)\n");
我收到以下错误。
FRANCE = 1 234 (I wish to have 1 234,00)
FRANCE = 1 234,567 (I wish to have 1 234,567)
FRANCE = 1 234,568 (I wish to have 1 234,567)
Exception in thread "main" java.lang.IllegalArgumentException: Malformed pattern "# ##0,00#"
我可以做些以上定制的数字格式吗?
最佳答案
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(Locale.FRANCE);
NumberFormat goodNumberFormat = new DecimalFormat("#,##0.00#", dfs);