255

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.

iajrz
  • 709
  • 6
  • 16
realtebo
  • 21,458
  • 34
  • 99
  • 169

6 Answers6

630

You can use:

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

See also the javadocs

beny23
  • 33,347
  • 4
  • 83
  • 84
  • 1
    What if myNumber is a double? – Fra Jan 12 '17 at 02:37
  • 8
    @Fra, then you would use `String.format("%02.0f", myNumber)` if you don't want the numbers after the decimal point – beny23 Jan 23 '17 at 12:51
  • 1
    For those who want to read specifically about the string format syntax: [Format String Syntax](https://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax) – Pony Apr 03 '18 at 14:35
  • 1
    This will generate an Android Linter Warning "Implicitly using the default locale is a common source of bugs: Use String.format(Locale, ...) instead" – Christopher Stock Feb 15 '19 at 10:36
  • 1
    @ChristopherStock That's a completely separate issue, to do with using the correct default locale of the device the app is running on - you can ignore or fix it, but that's related to Android and locales only. Nothing to do with the actual string formatting – Radu Apr 03 '19 at 13:45
  • If, like me, this answer didnt help you and you feel frustrated, please see https://stackoverflow.com/a/29882814/11561121 – Haha Jun 24 '21 at 16:32
66

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);
Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
  • 3
    Using a format is by far the slowest, but it is clearer and less unlikely to go horribly wrong. e.g. if num is -1. ;) – Peter Lawrey Sep 14 '12 at 09:23
53

You can use this:

NumberFormat formatter = new DecimalFormat("00");  
String s = formatter.format(1); // ----> 01
Daniel André
  • 1,108
  • 1
  • 12
  • 27
  • 1
    This should be the accepted answer! The result of the solution via String.format may vary due to locale settings. (s. Android Linter Warning "Implicitly using the default locale is a common source of bugs: Use String.format(Locale, ...) ) – Christopher Stock Feb 15 '19 at 10:38
  • Thanks. This also works with negatives: -2 --> -02 – Kirill Ch Oct 14 '21 at 17:58
4

The String class comes with the format abilities:

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

for full documentation, here is the doc

Grimmy
  • 806
  • 6
  • 16
4

In android resources it's rather simple

<string name="smth">%1$02d</string>
Vlad
  • 6,741
  • 2
  • 48
  • 42
2

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