5

How do I represent numbers in the format

001 = 1
002 = 2
003 = 3
010 = 10
020 = 20

The number of digits is always 3.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
Dave
  • 4,184
  • 8
  • 40
  • 46
  • 2
    You need to clarify your question. It's difficult to infer what you need by reading your post. Keep in mind that in Java, if you trail a number literal with `0` it means it's an octal number. – Pablo Santa Cruz Dec 07 '10 at 13:43
  • 1
    Do you mean what data structure to use, or how to format the number properly for display? – Eyal Schneider Dec 07 '10 at 13:43

4 Answers4

11

If you want to output integers such that they always have leading zeros, use String.format with a zero before the number of digits in the format string, for example:

int i = 3;
String s = String.format("%03d", i);
System.out.println(s);

Gives the output:

003
John Pickup
  • 5,015
  • 2
  • 22
  • 15
  • Indeed, although it is likely the poster wants to do something other than simply send the string to stdout. Maybe I should split the example to show explicitly how to construct the string... (I'll do that now) – John Pickup Dec 07 '10 at 13:59
  • Why is my eclipse saying I need to make i an Object[]? It won't let me make it an int. – Gareth Jan 24 '13 at 08:39
  • @Gareth: I guess you disabled autoboxing. Literally it reads `String.format("%03d", new Object[]{Integer.valueOf(i)});`. There are two objects created, one for varargs and one for autoboxing. – maaartinus Feb 04 '14 at 02:08
  • @maaartinus yep that was it. Figured it out after some coffee. Miracle drug that stuff. ;) – Gareth Feb 04 '14 at 07:46
1

Integer.valueOf("020") is sufficient for your purpose. It will give you 20 as a result. After that you can use it as Integer, int or String.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
1

You can use something like this

DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumIntegerDigits(3);
System.err.println(decimalFormat.format(2));
Vinay Lodha
  • 2,185
  • 20
  • 29
-1

Am I missing something obvious here?

String  num_str = "001"
Integer val     = Integer.parseInt(num_str);
String  answer  = val.toString();
Andrew White
  • 52,720
  • 19
  • 113
  • 137