17

I'm using an int variable:

month = dp.getMonth() + 1;

currently getting an output of "2" and when I do the following:

if (month<10){
                month = '0'+month;
            };

I get: 50.

Robby
  • 173
  • 1
  • 1
  • 4

1 Answers1

66

Your problem is that your '0' char is being coerced to an integer. Since '0' has an ASCII value of 48, you're getting 48 + 2 = 50.

Note that what you're trying to do won't work - you can't add a leading 0 to month, as month is a number. A leading zero only makes sense in a string representation of a number.

As explained in this answer, here's how to produce a zero-padded number:

String.format("%02d", month);   
Community
  • 1
  • 1
Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77