1

I couldn't really clarify what I'm asking in the title. I an integer for a day and a month. I have to print the month with a 0 in front of it if it's one digit only.

For example 04 if month = 4 and so on.

This is how it's supposed to look like in C#:

Console.WriteLine("{0}.{1:00}", day, month);

Thank you.

  • Possible duplicate of [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) – dahrens Nov 19 '16 at 17:00

2 Answers2

0
int month = 4;
DecimalFormat formater = new DecimalFormat("00");
String month_formated = formater.format(month);
0

Besides the answer Fernando Lahoz provided (which is pretty specific to your case: decimal formating) you can also use System.out.format in Java which allows you to specify a format-string while printing to System.out (the format function is applicable to any PrintStream though). In your case

System.out.format("%2d %2d", day, month)

should do the trick. The %dis used for decimal integers and you can then specify any width you want just before the 'd' (2 in your case).

If you want to access the string formed for later use and not (only) print it you can use String.format. It uses the same format as System.out.format but returns the String that is formed.

A complete syntax for all formats(string, decimal, floating point, calendar, date/time, ...) can be found here. If you'd like a quick tuto on number-formatting you can check this link or this link instead.

Good luck!

Community
  • 1
  • 1
J.Baoby
  • 1,915
  • 2
  • 9
  • 17