How do I format a long integer as a string without separator in Java?

Simple question, but I'll bet that asking on here will probably be more straight forward than trying to understand the documentation for MessageFormat:

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

Observed value is "12,345".

Desired value is "12345".


Solution 1:

MessageFormat.format("{0,number,#}", foo);

Solution 2:

Just use Long.toString(long foo)

Solution 3:

I struggled with this a little bit when trying to do "real world" patterns with internationalization, etc. Specifically, we have a need to use a "choice" format where the output depends upon the values being displayed, and that's what java.text.ChoiceFormat is for.

Here is an example for how to get this done:

    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));
    }

This generates the following output; I hope it's helpful for others who are trying to accomplish the same types of things:

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

As you can see, the "choice" format allows us to choose the type of format to use depending upon the value being passed-in to be formatted. Small numbers can be replaced with text (no display of the original value). Medium-sized numbers are shown with no grouping separators (no commas). The largest numbers do include the commas, again. Obviously, this is an entirely contrived example to demonstrate the flexibility of 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.