How to format a number 0..9 to display with 2 digits (it's NOT a date) How to format a number 0..9 to display with 2 digits (it's NOT a date) java java

How to format a number 0..9 to display with 2 digits (it's NOT a date)


You can use:

String.format("%02d", myNumber)

See also the javadocs


If you need to print the number you can use printf

System.out.printf("%02d", num);

You can use

String.format("%02d", num);

or

(num < 10 ? "0" : "") + num;

or

(""+(100+num)).substring(1);


You can use this:

NumberFormat formatter = new DecimalFormat("00");  String s = formatter.format(1); // ----> 01