Velocity Reviews > Java > Number format (ex: 5 as 00005)

# Number format (ex: 5 as 00005)

Patricia Shanahan
Guest
Posts: n/a

 11-10-2006
m wrote:
> Hi All
>
> Can you please tell me a way in which I can display a number with
> leading 0's. The total length of the number will be 5 digits.
>
> Ex: 5 as 00005, 25 as 00025, 125 as 00125 etc.
> I have a sequence which goes from 1 to a max of 99999.
>
> I know I can do it like this ..
> If (length(number)==1) { "0000"+number}
> else if (length(number)==2) { "000"+number}
>
> I am looking for any better solution. I use jdk1.5.0
>
> Thanks
>

Although all the suggested methods work for the particular case of 1
through 99999, in general I would avoid the manual methods and stick
with using either printf or a DecimalFormat.

Both automate reasonable handling of more general cases, such as
negative numbers and numbers that are greater than 99999, without
dropping information. You are likely to need to use the supplied methods
for some cases, so why not learn and use them even when you could do it
manually without too many special cases?

Patricia

trippy
Guest
Posts: n/a

 11-10-2006
In article <(E-Mail Removed). com>, m
took the hamburger meat, threw it on the grill, and I said "Oh Wow"...

> Hi All
>
> Can you please tell me a way in which I can display a number with
> leading 0's. The total length of the number will be 5 digits.
>
> Ex: 5 as 00005, 25 as 00025, 125 as 00125 etc.
> I have a sequence which goes from 1 to a max of 99999.
>
> I know I can do it like this ..
> If (length(number)==1) { "0000"+number}
> else if (length(number)==2) { "000"+number}
>
> I am looking for any better solution. I use jdk1.5.0
>
> Thanks
>
>

public String pimpMyNumber(int aNumber) {

DecimalFormat df = new DecimalFormat("000,000");
StringBuffer sb = df.format(aNumber);
return sb.toString();

}

--
trippy
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM

NP: "All I Really Want" -- Alanis Morissette

"Now, technology's getting better all the time and that's fine,
but most of the time all you need is a stick of gum, a pocketknife,
and a smile."

-- Robert Redford "Spy Game"