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.

7
  • 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 .. Commented Aug 7, 2012 at 17:53
  • First of all, int can represent value much larger than 99. If you need such representation, make your own class. Commented Aug 7, 2012 at 17:54
  • 2
    I think you are looking for something like this: Format an Integer using Java String Format Commented Aug 7, 2012 at 17:56
  • possible duplicate of [0 is added but not shown as two digit when converted to int ](stackoverflow.com/questions/11850609/…) Commented Aug 12, 2012 at 16:42
  • @Mist4u, have you ever worked with COBOL? :-D Commented Sep 28, 2013 at 15:03

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

21
// 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)

1 Comment

Should be "%02d" instead of "%2d"
6

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

Comments

5

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.