Java String.format(): Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
No edit summary
Line 11: Line 11:
* [[java MessageFormat|MessageFormat]]
* [[java MessageFormat|MessageFormat]]


=String=


 
<pre>
!!!Samples
 
!!!String
 
{{{
String arg = "blah"
String arg = "blah"
String.format("%1$-50s", arg);
String.format("%1$-50s", arg);
}}}
<pre>


This formats the first argument (%1$) as a string "s", to occupy at least 50 characters (width) and it left-justifies it ("-").
This formats the first argument (%1$) as a string "s", to occupy at least 50 characters (width) and it left-justifies it ("-").
Line 26: Line 22:
For general argument types, the precision is the maximum number of characters to be written to the output.
For general argument types, the precision is the maximum number of characters to be written to the output.


!!!Floating Point
=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:
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:


{{{
<pre>
double arg = 77.999
double arg = 77.999
String.format("%1$.2f", arg);
String.format("%1$.2f", arg);
}}}
</pre>


will display "78.00"
will display "78.00"


=Integer=


!!!Integer
<pre>
 
 
{{{
int arg = 77
int arg = 77
String.format("%1$3d", arg);
String.format("%1$3d", arg);
}}}
</pre>


will display " 77"
will display " 77"
__Referenced by:__\\
[{INSERT com.ecyrd.jspwiki.plugin.ReferringPagesPlugin WHERE max=20, maxwidth=50}]

Revision as of 17:58, 22 January 2016

External

Internal

String

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

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.

=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:

<pre>
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"