Formatting strings for C # integers

I have a class that contains two lines: one that reflects the current year and one that represents some kind of value. These fields are combined based on the format (uses string.format) that the user specified. IMPORTANT: the user entered the data that was generated, so he was always an integer, and we did not have to worry about it.

Our default format is "{0} - {1: 000}". However, now that the user has specified the data, this is a string that he does not want to format accordingly. Here is an example:

The user enters 12 as the required data. When formatting, instead of displaying 2011-0012, only 2011-12 is displayed. How can I make sure that 0 is added without any crazy loop that will add 0 or try to parse the number (assuming it is a number. 0 is enough to equal a string of length 4)?

Here is what I tried as a format:

"{0} - {1: 0000}" → the original format when the user was forced to enter numbers. "{0} - {1: D4}" "{0} - {1: N4}"

+4
source share
2 answers

You can use string.PadLeft() :

 string output = string.Format("{0}-{1}", "2011", input.PadLeft(4, '0')); 
+5
source

You can use string.PadLeft to add zeros to the left, or use int.TryParse to try to convert an integer. The latter will be doubled as a validation check.

+2
source

All Articles