Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adjusting padding formats

 
manish ahuja
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NumberFormat numberFormat = new DecimalFormat("00000000000000000000");

?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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() )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic