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

JavaNumber Formatting

Java Problem Overview


I'd like to always show a number under 100 with 2 digits (example: 03, 05, 15...)

How can I append the 0 without using a conditional to check if it's under 10?

I need to append the result to another String, so I cannot use printf.

Java Solutions


Solution 1 - Java

You can use:

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

See also the javadocs

Solution 2 - Java

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);

Solution 3 - Java

You can use this:

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

Solution 4 - Java

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

Solution 5 - Java

In android resources it's rather simple

<string name="smth">%1$02d</string>

Solution 6 - Java

I know that is late to respond, but there are a basic way to do it, with no libraries. If your number is less than 100, then:

(number/100).toFixed(2).toString().slice(2);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrealteboView Question on Stackoverflow
Solution 1 - Javabeny23View Answer on Stackoverflow
Solution 2 - JavaPeter LawreyView Answer on Stackoverflow
Solution 3 - JavaDaniel AndréView Answer on Stackoverflow
Solution 4 - JavaGrimmyView Answer on Stackoverflow
Solution 5 - JavaVladView Answer on Stackoverflow
Solution 6 - JavaArturo Viñas SalazarView Answer on Stackoverflow