I have the following Long: 201700112345
, and I want to convert it to 2017.001.12345
.
I know I could just use a substring:
long l = 201700112345L;
String s = Long.toString(l);
String result = s.substring(0,4)+"."+s.substring(4,7)+"."+s.substring(7);
But can I also accomplish this with a String.format
EDIT: ..with a single input for the Object-varargs parameter of the String.format
method?
Some things I've tried:
String.format("%4d.%3d.%5d", l);
// Which resulted in:
java.util.MissingFormatArgumentException: Format specifier '%3d'
Which is quite obvious I realize, because I only have one input instead of three..
I know I can backtrack to the same input using %1$
, so I then tried:
String.format("%4d.%1$3d.%1$5d", l);
// Which resulted in:
201700112345.201700112345.201700112345
I also tried this, which gave the correct lengths, but not the correct parts:
String.format("%.4s.%1$.3s.%1$.5s", Long.toString(l));
// Which resulted in:
2017.201.20170
I must admit I haven't used String.format
all that often, so I'm not too sure if it's even possible to have some kind of substring as format. And if it is possible, I can't figure it out..