Java Equivalent for sprintf
By Scott Hommel-Oracle on Dec 18, 2007
I was reading your tutorial on format. You can do something likeSystem.out.format ("a = %05d\\n", 32 )which should printa = 00032This is equivalent to
printf( "a = %5.5d\\n", a );in C++. I want to simulate
sprintfin Java, like:char b; sprintf( b, "%5.5d", 22);then
bwould contain the string
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
gcontained the integer value
22, I would want something like
00022instead of just
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
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
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