Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 20116
  • Last Modified:

Left pad with zeros

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
mhunts
Asked:
mhunts
  • 2
  • 2
1 Solution
 
Ajay-SinghCommented:
you should use NumberFormat class in order to do this
0
 
CEHJCommented:
public static String leftPad(int n, int padding) {
    return String.format("%0" + padding + "d", n);
}
0
 
CEHJCommented:
:-)
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!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now