TechFundu

  • Increase font size
  • Default font size
  • Decrease font size
Welcome Guest,  Login | Join Now
Home Blogs Left and Right Padding a String or Number in Java

Left and Right Padding a String or Number in Java


Posted by: rsrawat in Tech Blogs

Tagged in: java

Recently I tried a simple java program for left and right pad a Number with zeros.

I have gone through java.util.Formatter class but Unfortunately even after 6 major releases also Java String class doesn't have functions for these basic operations like StringUtils class of Apache Commons Lang provides.

http://commons.apache.org/lang/apidocs/org/apache/commons/lang/StringUtils.html

Left pad a String with a specified character.
static String leftPad(String str, int size, char padChar)
Right pad a String with a specified character.
static String rightPad(String str, int size, char padChar)

You can easily left pad a number with zeros using String.format(String format, Object... args) or DecimalFormat but I could not find any solution for right padding a number with zeros.

May be I am missing something, but would love to hear if any other java developer has solution for right padding number or string with zeros.

String.format("%1$05d", (int)123) returns '00123' or you can create DecimalFormat like new DecimalFormat("#####") and apply to any number but both of them do left padding

Formatter class document says for a number conversion (i.e. for 'd') if '-' flag is given then the padding will be on the right but it also says If both the '-' and '0' flags are given then an IllegalFormatFlagsException will be thrown.

So what are other ways to right pad a number in JDK?


Follow us on Twitter