• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Adjusting padding formats

 
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
NumberFormat numberFormat = new DecimalFormat("00000000000000000000");

?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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() )
 
We don't have time for this. We've gotta save the moon! Or check this out:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic