String Formatting for Integers c#
I have a class that contains two strings, one that reflects the current year and one that represents some value. These fields are combined based on a format (uses string.format) that is specified by the user. IMPORTANT: The user entered data used to be generated so it was always an integer and we didn't have to worry about this.
Our default format is "{0}-{1:000}". However, now that the user specified data is a string it does not want to format appropriately. Here is an example:
The user enters 12 as there required data. When formatting, instead of displaying 2011-0012, it is only displaying 2011-12. How can I make sure that the 0's are added without doing some crazy loop that will append the 0's or attempting to parse the number (assuming开发者_开发问答 that it is a number. There should only be enough 0's to equal a string of length 4)?
Here is what I have tried as a format:
"{0}-{1:0000}" -> the original format when the user was forced to enter numbers. "{0}-{1:D4}" "{0}-{1:N4}"
You could use string.PadLeft()
:
string output = string.Format("{0}-{1}", "2011", input.PadLeft(4, '0'));
You can use string.PadLeft
to add the zeros to the left, or use int.TryParse
to attempt conversion to an integer. The latter will double up as your validation check.
精彩评论