0

I generate a random number between 0-99 using this :

int num2= (int)(Math.random() * ((99) + 1));

When the number is below 10 I want it to print with a 0num2 So if the number is 9 it would be 09.

How can I get it to print this?

pb2q
  • 58,613
  • 19
  • 146
  • 147
user1695423
  • 65
  • 1
  • 2
  • 7

5 Answers5

5

You can use the format() method:

System.out.format("%02d%n", num2);

%02d prints the argument as a number with width 2, padded with 0's
%n gives you a newline

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Keppil
  • 45,603
  • 8
  • 97
  • 119
3
System.out.println((num2 < 10 ? "0" : "") + num2);

One liner :-)

arshajii
  • 127,459
  • 24
  • 238
  • 287
2
String str;
if (num2 < 10) str = "0" + num2;
else str = "" + num2;

System.out.println("Value is: " + str);
Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
2

Have a look at PrintStream.format, which will allow you to print using specified widths and padding characters.

System.out is a PrintStream, so you can use System.out.format in place of println.

Your case is pretty simple, look over the syntax for the format string:

System.out.format("%02d", num2);

Here 2 is the minimum width, and the 0 specifies that the result be padded with zeros, if the width of the result is less than 2.

pb2q
  • 58,613
  • 19
  • 146
  • 147
1

You can use the approach of removing an extra digit instead.

System.out.println(("" + (int)(Math.random()*100 + 100)).substring(1));

or to use the String format.

String s = String.format("%02d", (int)(Math.random()*100));

or

System.out.printf("%02d", (int)(Math.random()*100));

I would generally use the last option as it allows you to combine other strings and print them.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Do you think that would be better than appending an extra 0 if needed? If so, why? Also, you're getting a number from 100 to 199, not 0 to 99. But I hope you knew that. – Simon Forsberg Sep 24 '12 at 19:47
  • After removing the first digit 100 to 199 becomes 00 to 99. As to whether its better is a matter of taste. – Peter Lawrey Sep 24 '12 at 19:49
  • It makes the code both harder to read and, most likely, slower (even though a very tiny bit)... Don't see any point at all in using substring to do the job. – Simon Forsberg Sep 24 '12 at 19:53