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

60,820

Solution 1

Just use Long.toString(long foo)

Solution 2

MessageFormat.format("{0,number,#}", 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.

Share:
60,820
Daniel Fortunov
Author by

Daniel Fortunov

Daniel Fortunov holds a First-Class BSc Honours degree in Applied Computer Science and Cybernetics from the University of Reading, where he was awarded the Usher/Whitfield Cybernetics Prize for Best BSc/BEng Degree Result and travelled to New York to present original research at the IEEE EMBS conference. He currently works in London as a software developer in the financial sector.

Updated on May 08, 2020

Comments

  • Daniel Fortunov
    Daniel Fortunov about 4 years

    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".

  • Vishy
    Vishy over 14 years
    String.valueOf() calls Long.toString()
  • John K
    John K almost 14 years
    Maybe this is trifling but in this case you're relying on an undocumented behavior of Long.toString(foo). For that reason, I prefer Daniel Fortunov's answer.
  • Rob H
    Rob H almost 14 years
  • John K
    John K almost 14 years
    Rob H: Oh, you're right, though I'd point at the docs for Long#toString(long, int)
  • Philihp Busby
    Philihp Busby over 12 years
    Thanks, I was trying to do this with MessageFormat properties injection. Good thing there's more than one way to do it!
  • Pascal
    Pascal over 12 years
    i prefer this way. since it allows me to change the format in my language properties file.
  • A Gupta
    A Gupta over 9 years
    Nice..!! @daniel-fortunov Can you please explain what and how its done ?
  • Ofer Lando
    Ofer Lando about 9 years
    Perfect solution! Helped me keep the format/unformat option in reference data instead of at code level - thanks! And as @SebastianRoth said - this should have been the accepted answer.
  • keiki
    keiki about 9 years
    Unnecessary object creation. Never use new with wrapper classes.
  • Guillaume Husta
    Guillaume Husta over 8 years
    OK, however this solution is not applicable to message formatting in ResourceBundle. Tuto i18n
  • randers
    randers over 8 years
    And, as always, this expands to new StringBuilder("").append(foo).toString() so it's not really optimal.
  • Vishy
    Vishy over 8 years
    @RAnders00 Converting a number into a single string is unlikely to be the most optimal option, depending on the context you can usually avoid it entirely, but for the simplest pattern you can use ""+
  • randers
    randers over 8 years
    You are right, but I just wanted to point it out since people always tend to point it out.
  • Vishy
    Vishy over 8 years
    @RAnders00 btw using a message format is an order of magnitude more expensive, and more complicated in this case.
  • randers
    randers over 8 years
    Yeah, one should instead use Long.toString() since it's what this solution uses in the background anyways :)
  • Vishy
    Vishy over 8 years
    @RAnders00 ... unless you value your developer time more than your CPU time (which is usually the case)
  • Jean-François Beauchef
    Jean-François Beauchef about 8 years
    If you are using resource bundles, then Daniel Fortunov's answer is definitely preferable.
  • William
    William about 8 years
    This doesn't not work for Java8. Locale still intrudes and if your locale has setGroupingUsed==true then you will get grouping symbols injected. Very problematic if you only want certain integers to not have default locale grouping symbols.
  • humblerookie
    humblerookie about 7 years
    I'm actually surprised why prettying numeric strings a default and not an explicit thing with the formatter API
  • Aquarelle
    Aquarelle over 6 years
    This worked perfectly, thank you. I'm using the buildnumber Maven plugin and it kept formatting the build number with a comma, no matter what I put inside the <format> element.
  • GOTO 0
    GOTO 0 over 6 years
    This works also inside a choice format if you quote the pattern: MessageFormat.format("{0,choice,0#no foos|1#one foo|1<'{0,number,#}' foos}"
  • Christopher Schultz
    Christopher Schultz about 4 years
    @GOTO0 I only just noticed that way back in 2017 you posted this comment. No up-votes so it was hidden to me (hopefully fixed now!). My posted answer basically says the same thing, with a much more elaborate example.
  • Bruce wayne - The Geek Killer
    Bruce wayne - The Geek Killer over 2 years
    This works. I searched a lot and got this solution.
  • Bruce wayne - The Geek Killer
    Bruce wayne - The Geek Killer over 2 years
    Need a solution for property file, not code wise.
  • Brice
    Brice about 2 years
    Wow kudos for digging this one, and it's been there since Java 1.1 !