Wednesday, February 17, 2010

Left padding numbers

Again, a simple task: take a random unsigned integer up to 9999, and return it to the caller, but in a string which is always four characters (even though the random number may be one, two or three characters (like 2, 98, 112; I would be expecting 0002, 0098, 0112).

Took like ten minutes to find the right thing in the docs. But finally.

int randomNumber = randomGenerator.nextInt(9999);
System.out.println(String.format("%04d", randomNumber));


2213
0060
8492
8872
0064
5808
1552
0458
7856
8925

No comments:

Post a Comment