-2

I want to make an integer value from the range 1-9999. But the integer values should be always in 4 digits.

Like 0001, 0002, 0015, 0156, 1578

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dylen Wolff
  • 27
  • 1
  • 2
  • 1
    You'd need to use a string pad function, or you could have a string with some numeric characters. My guess is the former is what you're looking for. – Philip Rollins Aug 25 '16 at 02:35
  • 1
    You are mixing up different concepts. Integers are just **numbers**. And 1, as a number is always that: a 1. It doesn't know about "leading zeros". What you are talking about is a **string** representing a number. Because then, strings can have a fixed length, and then you might add leading zeros to enhance "number 1" to "0001". – GhostCat Aug 25 '16 at 02:49

3 Answers3

7

You can probably use String format of the integer you willing to, like this:

String.format("%04d", your integer));

This will always show missing 0 on the left on digits like 01 or 1.

Jose Bernhardt
  • 887
  • 1
  • 10
  • 24
2
System.out.format("%04d%n", n);    
desertnaut
  • 57,590
  • 26
  • 140
  • 166
ThanatosDM
  • 21
  • 3
1

If you want to print 4 digit integer:

System.out.printf("%04d%n",your integer);

If you want to store in a variable:

String str=String.format("%04d", your integer));

Read more details about String format()

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Santosh Kumar
  • 552
  • 4
  • 13