?
Solved

Left pad with zeros

Posted on 2006-11-17
4
Medium Priority
?
20,113 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 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month12 days, 7 hours left to enroll

777 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