com/format-java
And:
We specify, after the "$" sign that we want
to insert numbers (digits) with the
lowercase "d" char.
Result:
Format yields a composed string containing text (number
words), punctuation, and numeric values.
Output
1 de 6 09/05/17 15:33
Java String.format Examples: Numbers and Stri... https://www.dotnetperls.com/format-java
Output
00000 00010
00001 00011
00002 00012
00003 00013
00004 00014
Note:
As this example shows, the "f" format
will round the number up, not truncate digits.
Output
Index:
It helps to use an index to reference the argument (like "%1") if
we reuse the argument, or the references are dierent in order.
Opinion:
I think just using "%s" when possible yields the clearest,
easiest-to-read code. Keep it simple.
2 de 6 09/05/17 15:33
Java String.format Examples: Numbers and Stri... https://www.dotnetperls.com/format-java
Output
Marcus Aurelius
Marcus Aurelius
Marcus Aurelius
Output
100 ART1
Right:
To specify padding on the right (ten
spaces on the right) we use -10s. The result string is 10 chars.
Left:
To add padding to the left (right justify text) to 10 chars, we use
10s. No plus sign is used.
3 de 6 09/05/17 15:33
Java String.format Examples: Numbers and Stri... https://www.dotnetperls.com/format-java
Output
cat orange
dog black
bird blue
elephant grey
Note:
We use the "%1" at the start of the insertion points to indicate
"the rst argument" after the format string.
import java.util.Calendar;
Output
4 de 6 09/05/17 15:33
Java String.format Examples: Numbers and Stri... https://www.dotnetperls.com/format-java
Month:
The uppercase "B" is along month name
like February. The lowercase "b" is a
short name like Feb. And "m" means the month number.
Day:
With "A" we use the long day name like Wednesday. With "a" we
specify the short name like Wed. The "d" is a day number.
Year:
An uppercase Y is the long year like 2015. A lowercase "y" is a
two-digit year. A "j" is the day number in an entire year.
import java.util.Calendar;
Output
Hours:
We use the chars "HIkl" to format
hours. The H means 2-digits on the 24-hour clock. The "k" is the
same as H but has no leading 0.
Hours, 12-hour:
The 12-hour clock requires the uppercase letter I in the format.
With "l" we have the same thing but with no leading 0.
AM/PM:
The dierence between AM and PM is critical in life. With the
lowercase p format code we get am and pm strings.
5 de 6 09/05/17 15:33
Java String.format Examples: Numbers and Stri... https://www.dotnetperls.com/format-java
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
// Format minute.
result = String.format("Minute: %1$tM", cal);
System.out.println(result);
Output
Hour: 18 06 18 6
Minute: 53
Second: 23
AM/PM: pm
6 de 6 09/05/17 15:33