-1

How do I format a parsed String?

For example:

ph = "0412456839";
n = Long.parseLong(ph);

When I print n, I get (Without 0):

412456839

I want to print the same as ph. I could always do

System.out.println("0"+n);

but is there a way to format it?

2 Answers2

3

Using java.util.Formatter

System.out.printf("%010d\n", n);

    % 0 10 d
      ^  ^ ^
      |  | decimal
      |  width
      zero-pad

If you need the output in a String instead of writing to System.out, use

String s = String.format("%010d", n);
Jim Garrison
  • 81,234
  • 19
  • 144
  • 183
0

You could create a DecimalFormat. That would allow you to format a number into a string using your own formatting rules. In this case, it is formatting it to be a 10 digit number that includes preceding zeros.

String ph = "0412456839";
Long n = Long.parseLong(ph);
String formattedN = new DecimalFormat("0000000000").format(n);
System.out.println(formattedN);

if you are using Apache Commons, you can use:

   int paddingLength = 10;
   String paddingCharacter = "0";
   StringUtils.leftPad("" + n, paddingLength, paddingCharacter);
Adam
  • 39,529
  • 15
  • 101
  • 139