| Author |
Adjusting padding formats
|
manish ahuja
Ranch Hand
Joined: Oct 23, 2003
Posts: 312
|
|
Hi there, Currently I have a int variable which can be of varying size 14,15,16 and I want to construct a String variable of size 20. I am using java.text.NumberFormat and DecimalFormat classes for the same So accordingly there should be 6 preceding zeros in case length is 14, 5 preceding zeros when length is 15 and 4 preceding zeros when length is 16. Currently I have a static number format something like this NumberFormat numberFormat = new DecimalFormat("00000"); how can i make it more generic where I can specify the total length of the String and adjust the preceding zeros accordingly Regards,
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
NumberFormat numberFormat = new DecimalFormat("00000000000000000000"); ?
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
One way is to make a loop that prepends zeros until the string gets to the length you want. You can make that generic and specify the character to pad with, too. result = rightJustify( "" + myInt, 20, "0" ); A less flexible way - because we hard code the 20 zeros - is to prepend the zeros and substring: result = "" + myInt result = ("0000000000000000000000" + result).substring( result.length() )
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
 |
|
|
subject: Adjusting padding formats
|
|
|