Solved

Left pad with zeros

Posted on 2006-11-17
4
20,102 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 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

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

717 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