141

简单的问题,但我敢打赌,在这里提问可能比试图理解以下文档更直接MessageFormat

long foo = 12345;
String s = MessageFormat.format("{0}", foo);

观测值为“12,345”。

所需值为“12345”。

4

6 回答 6

368
MessageFormat.format("{0,number,#}", foo);
于 2009-12-21T19:38:52.107 回答
74

只需使用Long.toString(long foo)

于 2009-12-21T19:35:09.633 回答
2

在尝试使用国际化等进行“真实世界”模式时,我对此有点挣扎。具体来说,我们需要使用“选择”格式,其中输出取决于所显示的值,这就是java.text.ChoiceFormat目的。

以下是如何完成此操作的示例:

    MessageFormat fmt = new MessageFormat("{0,choice,0#zero!|1#one!|1<{0,number,'#'}|10000<big: {0}}");

    int[] nums = new int[] {
            0,
            1,
            100,
            1000,
            10000,
            100000,
            1000000,
            10000000
    };

    Object[] a = new Object[1];
    for(int num : nums) {
        a[0] = num;
        System.out.println(fmt.format(a));
    }

这会生成以下输出;我希望它对尝试完成相同类型事情的其他人有所帮助:

zero!
one!
100
1000
10000
big: 100,000
big: 1,000,000
big: 10,000,000

如您所见,“选择”格式允许我们根据传入的要格式化的值来选择要使用的格式类型。可以用文本替换小数字(不显示原始值)。中等大小的数字显示没有分组分隔符(没有逗号)。最大的数字确实包括逗号。显然,这是一个完全人为的例子来展示java.text.MessageFormat.

A note about the quoted # in the format text: since both ChoiceFormat and MessageFormat are being used, there is a collision between metacharacters between the two. ChoiceFormat uses # as a metacharacter that essentially means "equals" so that the formatting engine knows that e.g. in the case of 1#one! we are comparing {0} with 1, and if they are equal, it uses that particular "choice".

But # has another meaning to MessageFormat, and that's as a metacharacter which has meaning for DecimalFormat: it's a metacharacter which means "put a number here".

Because it's wrapped up in a ChoiceFormat string, the # needs to be quoted. When ChoiceFormat is done parsing the string, those quotes are removed when passing the subformats to MessageFormat (and then on to DecimalFormat).

So when you are using {0,choice,...}, you have to quote those # characters, and possibly others.

于 2020-05-07T14:44:25.393 回答
-2

作为替代方案String.formatjava.util.Formatter也可能对您有用...

于 2009-12-21T19:39:47.820 回答
-2

最短的方法是

long foo = 12345;
String s = ""+foo;
于 2010-01-04T10:59:50.093 回答
-6

你可以试试:

String s = new Long(foo).toString();
于 2009-12-22T04:51:30.960 回答