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

6

159

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

Homing answered 21/12, 2009 at 19:32 Comment(0)
J
82

Just use Long.toString(long foo)

Jarnagin answered 21/12, 2009 at 19:35 Comment(7)
String.valueOf() calls Long.toString()Yclept
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.Borough
It's not undocumented. See download.oracle.com/javase/6/docs/api/java/lang/….Jarnagin
Rob H: Oh, you're right, though I'd point at the docs for Long#toString(long, int)Borough
OK, however this solution is not applicable to message formatting in ResourceBundle. Tuto i18nSubequatorial
If you are using resource bundles, then Daniel Fortunov's answer is definitely preferable.Callery
IMO this is a better answer than the accepted one based upon the question. Had the question specified "how do I tell a resource bundle to display a number without separators" then the accepted one would be better.Confiscable
H
406
MessageFormat.format("{0,number,#}", foo);
Homing answered 21/12, 2009 at 19:38 Comment(10)
Thanks, I was trying to do this with MessageFormat properties injection. Good thing there's more than one way to do it!Camillacamille
i prefer this way. since it allows me to change the format in my language properties file.Swainson
Nice..!! @daniel-fortunov Can you please explain what and how its done ?Menstruum
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.Seaborne
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.Orvie
I'm actually surprised why prettying numeric strings a default and not an explicit thing with the formatter APIEuphrasy
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.Incurrence
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}"Justinejustinian
@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.Confiscable
This works. I searched a lot and got this solution.Inexecution
J
82

Just use Long.toString(long foo)

Jarnagin answered 21/12, 2009 at 19:35 Comment(7)
String.valueOf() calls Long.toString()Yclept
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.Borough
It's not undocumented. See download.oracle.com/javase/6/docs/api/java/lang/….Jarnagin
Rob H: Oh, you're right, though I'd point at the docs for Long#toString(long, int)Borough
OK, however this solution is not applicable to message formatting in ResourceBundle. Tuto i18nSubequatorial
If you are using resource bundles, then Daniel Fortunov's answer is definitely preferable.Callery
IMO this is a better answer than the accepted one based upon the question. Had the question specified "how do I tell a resource bundle to display a number without separators" then the accepted one would be better.Confiscable
C
4

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.

Confiscable answered 7/5, 2020 at 14:44 Comment(1)
Wow kudos for digging this one, and it's been there since Java 1.1 !Iceblink
Y
-1

The shortest way is

long foo = 12345;
String s = ""+foo;
Yclept answered 4/1, 2010 at 10:59 Comment(6)
And, as always, this expands to new StringBuilder("").append(foo).toString() so it's not really optimal.Leenaleeper
@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 ""+Yclept
You are right, but I just wanted to point it out since people always tend to point it out.Leenaleeper
@RAnders00 btw using a message format is an order of magnitude more expensive, and more complicated in this case.Yclept
Yeah, one should instead use Long.toString() since it's what this solution uses in the background anyways :)Leenaleeper
@RAnders00 ... unless you value your developer time more than your CPU time (which is usually the case)Yclept
C
-2

As an alternative String.format and java.util.Formatter might work for you as well...

Citizenship answered 21/12, 2009 at 19:39 Comment(1)
Need a solution for property file, not code wise.Inexecution
S
-6

You could try:

String s = new Long(foo).toString();
Sweatbox answered 22/12, 2009 at 4:51 Comment(1)
Unnecessary object creation. Never use new with wrapper classes.Create

© 2022 - 2024 — McMap. All rights reserved.