用逗号和自定义格式化的数字 [英] Custom formatted number with period and comma

查看:184
本文介绍了用逗号和自定义格式化的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题和其他几个与格式化小数有关的问题(所有这些都没有帮助我在这种情况下)



我正在尝试将一个Long格式化为一个字符串例如123456 - > 012.345,6(句点后加逗号,看起来很奇怪,这是一个项目需求)。

我正在试验格式化的DecimalFormat:

lockquote
private static final DecimalFormat format = new DecimalFormat(## 0.000,0);


然而,在实例化过程中抛出一个异常:


lang.IllegalArgumentException:格式错误## 0.000,0

我也尝试过预先将语言环境更改为EU系统,例如
$ b


NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.GERMAN);

如何以这种方式格式化数字? DecimalFormat是错误的解决方案吗?我可以使用NumberFormat吗?或者我需要一个自定义的格式化程序?

解决方案

您应该避免构建 DecimalFormat 直接。无论在目标语言环境中如何显示,逗号始终都是 用于模式定义中的分组。同样,句号总是用于小数。这看起来不合逻辑,但是必须记住这是一个模式定义,和#一样,这些字符描述了替换,而不是字符本身。

  NumberFormat f = NumberFormat.getInstance(Locale.GERMANY); 
if(f DecimalFormat的实例){
((DecimalFormat)f).applyPattern(## 0,000.0);
}
f.format(123456 / 10.0);

小数点后面的数字除以10是必须的。


Somewhat related to this question and several other SO questions relating to formatting decimals (all of which did not help me in this instance).

I am trying to format a Long into a String e.g. 123456 -> 012.345,6 (period followed by comma as strange as it may seem, it's a project requirement).

I am experimenting with DecimalFormat for the formatting:

private static final DecimalFormat format = new DecimalFormat("##0.000,0");

However it throws an exception during instantiation:

java.lang.IllegalArgumentException: Malformed pattern "##0.000,0"

I have also experimented with changing the locale to an EU system beforehand e.g.

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.GERMAN);

How can I format numbers in this way? Is DecimalFormat the wrong solution? Can I use a NumberFormat? Or will I need a custom formatter?

解决方案

You should avoid constructing DecimalFormat directly. Commas are always used for grouping in the pattern definition, regardless of how they appear in the target locale. Similarly, periods are always used for decimals. This appears illogical, but one must remember this is a pattern definition, and like #, these characters describe a replacement, not the character itself.

NumberFormat f = NumberFormat.getInstance(Locale.GERMANY);
if (f instanceof DecimalFormat) {
    ((DecimalFormat) f).applyPattern("##0,000.0");
}
f.format(123456 / 10.0);

The division by 10 is necessary to obtain a digit after the decimal point.

这篇关于用逗号和自定义格式化的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆