-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
  • 85,615
  • 20
  • 155
  • 190
  • In a Format String you can use `%n` for a system dependent newline (which may be `\n\r`) instead of `\n` – Felix Aug 25 '17 at 00:56
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
  • 43,763
  • 16
  • 104
  • 144