Java Equivalent for sprintf

We received this question on the Tutorial Feedback alias:

I was reading your tutorial on format. You can do something like
    System.out.format ("a = %05d\\n", 32 )
which should print
    a = 00032
This is equivalent to printf( "a = %5.5d\\n", a ); in C++. I want to simulate sprintf in Java, like:
    char b[20];

    sprintf( b, "%5.5d", 22);
then b would contain the string 00022.

That is, I want a way in Java to do an Integer.toString() but be able to specify a width and have it insert leading 0's. If g contained the integer value 22, I would want something like g.toString(5) to return 00022 instead of just "22" or " 22".

Any way to do that?


Why, yes, there are a couple ways to accomplish this!

If you are writing an application that must be localized and internationalized, you may want to use DecimalFormat, like this:

        DecimalFormat myFormatter = new DecimalFormat("00000");
        String s2 = myFormatter.format(22);

You can refer to the Internationalization tutorial for more information.

DecimalFormat uses the rather arcane text APIs. If you don't need something this heavy-duty, you may want to use the java.util.Formatter class, introduced in JDK 5. The String.format methods provide a front-end to the Formatter class. To accomplish the above task using String.format, the code would look like this:

        String s1 = String.format("'%05d'%n", 22);
If you want the output to go somewhere other than a string - to a file or to System.out, for example - you would probably use the Formatter class directly.

For further information, check out these pages in the tutorial:

If you are using an earlier release than JDK 5, you might be interested in this Formatted Printing for Java (sprintf) article.

As a result of this question, I've tweaked the tutorial a bit, so thanks for the feedback!

-- Sharon Zakhour

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Blog about Java technology documentation and news about Java releases.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today