Formatting an integer with leading zeros

G

GIMME

Is there a "java" way to format int values as strings with
leading zeros?

I've reviewed many posts and the solutions involved rolling
your own with prepending a "0" as necessary until getting
the desired result.

A far cry from C's %5d

Thanks
 
A

Anton Spaans

GIMME said:
Is there a "java" way to format int values as strings with
leading zeros?

I've reviewed many posts and the solutions involved rolling
your own with prepending a "0" as necessary until getting
the desired result.

A far cry from C's %5d

Thanks

Not necessary. Here is a sample that always prints at least 4 digits
(including leading zeros):

java.text.DecimalFormat nft = new
java.text.DecimalFormat("#0000.###");
nft.setDecimalSeparatorAlwaysShown(false);
System.out.println(nft.format(20));

-- Anton Spaans
 
N

Niels Ull Harremoës

GIMME said:
Is there a "java" way to format int values as strings with
leading zeros?

I've reviewed many posts and the solutions involved rolling
your own with prepending a "0" as necessary until getting
the desired result.
Take a look at java.text.DecimalFormat - e.g.

myFormat = new java.text.DecimalFormat("00000");
myFormat.format(new Integer(someValue));

There are many other formatting chars as well.
 
N

nos

GIMME said:
Is there a "java" way to format int values as strings with
leading zeros?

I've reviewed many posts and the solutions involved rolling
your own with prepending a "0" as necessary until getting
the desired result.

A far cry from C's %5d

Thanks

But is it a far cry from COBOL?
 
D

Dale King

GIMME said:
Is there a "java" way to format int values as strings with
leading zeros?

I've reviewed many posts and the solutions involved rolling
your own with prepending a "0" as necessary until getting
the desired result.

A far cry from C's %5d


Note in JDK1.5 you will get a Java equivalent of printf.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top