Java String.format(): Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 10: Line 10:
* [[java DecimalFormat|DecimalFormat]]
* [[java DecimalFormat|DecimalFormat]]
* [[java MessageFormat|MessageFormat]]
* [[java MessageFormat|MessageFormat]]
=Overview=
Format string:
<font size=-1>
%[argument_index$][flags][width][.precision]conversion
</font>


=String=
=String=

Revision as of 17:48, 26 August 2021

External

Internal

Overview

Format string:

%[argument_index$][flags][width][.precision]conversion

String

String arg = "blah"
String.format("%1$-50s", arg);

This formats the first argument (%1$) as a string "s", to occupy at least 50 characters (width) and it left-justifies it ("-").

For general argument types, the precision is the maximum number of characters to be written to the output.

Parameterized Width

int width=10;
String format = "%1$-" + width + "s";
String.format(format, s);

Floating Point

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. The conversion is done with rounding:

double arg = 77.999
String.format("%1$.2f", arg);

will display "78.00"

Integer

int arg = 77
String.format("%1$3d", arg);

will display " 77"

Hexadecimal Integer

Format string:

int i = 10;
String.format("%1$02x", i);

The result will be 0-padded (flag is "0"), will be displayed on two characters and more (width is 2) and it will be rendered as a hexadecimal (conversion is "x").