27

I would like to format a 3-digit integer to a 4-digit string value. Example:

int a = 800;
String b = "0800";

Of course the formatting will be done at String b statement. Thanks guys!

Melvin Lai
  • 861
  • 3
  • 17
  • 35

5 Answers5

63

Use String#format:

String b = String.format("%04d", a);

For other formats refer the documentation

AurA
  • 12,135
  • 7
  • 46
  • 63
Thilo
  • 257,207
  • 101
  • 511
  • 656
5

If you want to have it only once use String.format("%04d", number) - if you need it more often and want to centralize the pattern (e.g. config file) see the solution below.

Btw. there is an Oracle tutorial on number formatting.

To make it short:

import java.text.*;

public class Demo {

   static public void main(String[] args) {
      int value = 123;
      String pattern="0000";
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(output); // 0123
   }
}

Hope that helps. *Jost

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
Jost
  • 1,549
  • 12
  • 18
3

Please try

String.format("%04d", b);
wanana
  • 361
  • 1
  • 9
2
String b = "0" + a;

Could it be easier?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

You can always use Jodd Printf for that. In your case:

Printf.str("%04d", 800);

would do the job. This class was created before Sun added String.format and has somewhat more formatting options.

igr
  • 10,199
  • 13
  • 65
  • 111