26

How can I store an integer in two digit format in Java? Like can I set

int a=01;

and print it as 01? Also, not only printing, if I say int b=a;, b should also print its value as 01.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mistu4u
  • 5,132
  • 15
  • 53
  • 91
  • 4
    Integers are integers. *Assuming no octal notation* (which there is in Java literals) then 1 = 01 = 001 = .. You are looking to turn the **integer** into the **String** with that format .. –  Aug 07 '12 at 17:53
  • First of all, int can represent value much larger than 99. If you need such representation, make your own class. – Andrew Logvinov Aug 07 '12 at 17:54
  • 2
    I think you are looking for something like this: [Format an Integer using Java String Format](http://stackoverflow.com/questions/6034523/format-an-integer-using-java-string-format) – nkr Aug 07 '12 at 17:56
  • possible duplicate of [0 is added but not shown as two digit when converted to int ](http://stackoverflow.com/questions/11850609/0-is-added-but-not-shown-as-two-digit-when-converted-to-int) – Brad Mace Aug 12 '12 at 16:42
  • @Mist4u, have you ever worked with COBOL? :-D – Tassos Bassoukos Sep 28 '13 at 15:03
  • @TassosBassoukos, Nah! But please let me know how is COBOL funny? – Mistu4u Sep 29 '13 at 14:54
  • @Mistu4u Well, in COBOL there are number types that are preformatted (that is, the number type itself defines that f.e. this value is a 2-digit decimal number that has leading zeroes). – Tassos Bassoukos Sep 30 '13 at 13:19

4 Answers4

84

I think this is what you're looking for:

int a = 1;
DecimalFormat formatter = new DecimalFormat("00");
String aFormatted = formatter.format(a);

System.out.println(aFormatted);

Or, more briefly:

int a = 1;
System.out.println(new DecimalFormat("00").format(a));

An int just stores a quantity, and 01 and 1 represent the same quantity so they're stored the same way.

DecimalFormat builds a String that represents the quantity in a particular format.

treythomas123
  • 1,373
  • 1
  • 11
  • 11
20
// below, %02d says to java that I want my integer to be formatted as a 2 digit representation
String temp = String.format("%02d", yourIntValue);
// and if you want to do the reverse
int i = Integer.parse(temp);

// 2 -> 02 (for example)
Yusril Maulidan Raji
  • 1,682
  • 1
  • 21
  • 46
Joseph_Marzbani
  • 1,796
  • 4
  • 22
  • 36
6

This is not possible, because an integer is an integer. But you can format the Integer, if you want (DecimalFormat).

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
5

look at the below format its work above format can work for me

System.out.printf("%02d", myNumber)

Community
  • 1
  • 1
mbpatel
  • 501
  • 1
  • 5
  • 19