Java: Formatted conversion to String
Format conversion
You can use a format, a string which tells how you want values converted to string.
Formatting numbers with %d (integers) and %f (floating point)
The basic support is in the java.util.Formatter
class, where
a Formatter
object is created and it's format
method
is called. However, it's more common to use one of these convenience methods:
String.format(format, values...)
System.out.printf(format, values...)
orSystem.err.print.
Basic format structure for three types
- Formatting most values
%[argument_index$][flags][width][.precision]conversion
- Formating Calendar values
%[argument_index$][flags][width][.precision]conversion
- Non-argument values
%[flags][width]conversion
Like C's printf. If you are familiar with C's printf
formats,
you will be very comfortable with Java's formats, altho they are slightly
different.
Full description of formatting
Sun's Java documentation has a full description of the formatting codes. You should download the latest version of the API documentation. Here is a link to Java version 5 documentation: java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html .