24

How would I format an int between 0 and 99 to a string which is 2 chars. E.g

4  becomes "04"
36 becomes "36"

Thanks in advance.

3 Answers 3

54

Use String.format(). Example:

class Test{
    public static void main(String[]args){
        System.out.println(String.format("%02d", 42)); //42
        System.out.println(String.format("%02d",  7)); //07
    }
}

Edit:

luiscubal's comment got me thinking, so I figured why not benchmark the three alternatives.

import java.text.*;

interface Fmt{
    public String f(int x);
}

class Test{

    static NumberFormat formatter = new DecimalFormat("00");

    static Fmt f1 = new Fmt(){
        public String f(int x){ return ((x<10)?"0":"") + x; }
        public String toString(){return "f1";}
    };

    static Fmt f2 = new Fmt(){
        public String f(int x){ return String.format("%02d", x); }
        public String toString(){return "f2";}
    };

    static Fmt f3 = new Fmt(){
        public String f(int x){ return formatter.format(x); }
        public String toString(){return "f3";}
    };

    public static void main(String[]args){

        Fmt[] fmts = new Fmt[]{f1, f2, f3, f3, f2, f1};

        for (int x : new int[]{7, 42, 99}){

            String s0 = null;
            for (Fmt fmt : fmts)
                if (s0==null)
                    s0 = fmt.f(x);
                else
                    if (!fmt.f(x).equals(s0))
                        System.exit(1);

            System.out.printf("%02d\n", x);

            for (Fmt fmt : fmts){
                String s = null;
                int count = 0;
                System.gc();
                long t0 = System.nanoTime();
                for (int i=0; i<100000; i++){
                    count += fmt.f(x).length();
                }
                long t1 = System.nanoTime();

                System.out.printf("    %s:%8.2fms, count=%d\n",
                    fmt, (t1-t0)/1000000.0, count);
            }

        }
    }

}

The output I got was:

07
    f1:   11.28ms, count=200000
    f2:  195.97ms, count=200000
    f3:   45.41ms, count=200000
    f3:   39.67ms, count=200000
    f2:  164.46ms, count=200000
    f1:    6.58ms, count=200000
42
    f1:    5.25ms, count=200000
    f2:  163.87ms, count=200000
    f3:   42.78ms, count=200000
    f3:   42.45ms, count=200000
    f2:  163.87ms, count=200000
    f1:    5.15ms, count=200000
99
    f1:    5.83ms, count=200000
    f2:  168.59ms, count=200000
    f3:   42.86ms, count=200000
    f3:   42.96ms, count=200000
    f2:  165.48ms, count=200000
    f1:    5.22ms, count=200000

Turns out - if I tested correctly - that SpeedBirdNine had the most efficient solution, albeit badly presented. So I revise my solution to:

String answer = ((x<10)?"0":"") + x;

In retrospect I think it makes sense, given that my initial solution incurred the cost of parsing the format string, and I'd assume Anthony's formatter also has some manner of data structure behind it being iterated every time.

And predictably a lot faster by keeping a String[] containing all the 100 strings, but that's probably overkill...

Sign up to request clarification or add additional context in comments.

4 Comments

If performance is the primary concern, I don't think one should be using java -- I'm pretty sure that since the application here is some string formatting, performance is not the primary concern. Java's primary strength in this context is its comprehensive standard library, with features such as the one I highlighted in my comment above: support for internationalization and localization.
I've used formatters myself, and for the reasons you mentioned, which is why I'd +1ed your comment. I wasn't necessarily trying to make a point with my benchmark, rather I was curious how those alternatives paired against each other. But I do think there might exist legitimate use cases for having number formatting code somewhere in a Java inner loop, so I presented my results.
I agree -- I haven't used java for years, but I see it is used a lot on platforms such as Android, where there might be a case for optimization. It is quite interesting that String.format() has large overheads, it is probably instantiating an implementation of NumberFormat with every invocation.
You're right. String.format() instantiates a Formatter, and from then on it's a pretty involved process. I think there's a NumberFormat in there as well. Some huge switch statements, unboxing, edge cases etc.
7

You can do this using NumberFormat. E.g.,

NumberFormat formatter = new DecimalFormat("00");
String s = formatter.format(4); 

2 Comments

+1 for the answer. I'm going to use Vlad's answer though as it's short :)
@Ash Keep NumberFormat in mind though -- when it comes to internationalization and localization, you may need to use it instead of String formatters.
3

Simple way is to append "" to the integer (or any primitive type)

String str = "" + anyInetger;

You can use

String str;
if (anyInteger < 10)
{
    str = " 0" + anyInetger;
}
else
{
    str = "" + anyInetger;
}

4 Comments

Worth noting that your example will add an extra space to the integer, that integer is misspelled, and I find it hard to believe that concatenating empty string with an integer is the best way to convert that integer to a string.
@luiscubal it's the less verbose than Integer.toString(i); or using new StringBuffer(3).append('0').append(i).substring(i<10?0:1,i<10?2:3);
@luiscubal also add the fact that str is not visible after the if-else. +1 for efficiency though.
@Vlad Yeah I didn't see that one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.