left-padding ints

I

Ike

Is there something in the API for left-padding an int with, say, 0's when
converting to a String, such that, say 1 becomes "01" ? -Ike
 
C

Chris Smith

Ike said:
Is there something in the API for left-padding an int with, say, 0's when
converting to a String, such that, say 1 becomes "01" ? -Ike

Yep. See java.text.DecimalFormat or java.text.NumberFormat. For
DecimalFormat, simply use '0' characters instead of '#' characters in
the pattern. For NumberFormat, use setMinimumIntegerDigits. The
difference between the two is that NumberFormat is more flexible. If
you're sure that you want to display the result in a decimal number
system regardless of locale, then use DecimalFormat instead.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

Is there something in the API for left-padding an int with, say, 0's when
converting to a String, such that, say 1 becomes "01" ? -Ike

make a slight mod to this code:

/**
* Pads the string out to the given length by applying blanks on
the left.
*
* @param s
* String to be padded/chopped.
* @param newLen
* length of new String desired.
* @param chop
* true if Strings longer than newLen should be truncated
to newLen
* chars.
* @return String padded on left/chopped to the desired length.
*/
public final static String leftPad ( String s, int newLen, boolean
chop )
{
int grow = newLen - s.length();
if ( grow <= 0 )
{
if ( chop )
{
return s.substring( 0, newLen );
}
else
{
return s;
}
}
else if ( grow <= 30 )
{
return " ".substring( 0, grow
) + s;
}
else
{
return rep( ' ', grow ) + s;
}
} // end leftPad
 
J

Joan

Ike said:
Is there something in the API for left-padding an int with,
say, 0's when
converting to a String, such that, say 1 becomes "01" ? -Ike

// requires java 5.0
// not tested
int x = 5;
String s = String.format("%02d", x); // zero not oh
 

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,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top