Solved

Left pad with zeros

Posted on 2006-11-17
4
20,095 Views
Last Modified: 2011-08-18
I want a function that converts an int to String, with left padding of a specified number of zeros. I know I could do this with a loop, and count characters, but I want a simpler method. I thought there was something like that already in the JDK that did this.

Something like String leftPad(int numToCovert, int width) which would return the following:

leftPad(5, 3) would return "005"
leftPad(15, 5) would return "00015"
leftPad(224, 3) would return "224"
leftPad(0, 4) would return "0000"
leftPad(3335, 3) would throw an exception

I don't want you to write the method for me. I want you to tell me the JDK classes and methods that I should use. I would especially like to know if a "leftPad" method already exists.
0
Comment
Question by:mhunts
  • 2
  • 2
4 Comments
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17967747
you should use NumberFormat class in order to do this
0
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17967748
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 17967867
public static String leftPad(int n, int padding) {
    return String.format("%0" + padding + "d", n);
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17968390
:-)
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question