简体   繁体   English

整数的字符串格式c#

[英]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. 这些字段基于用户指定的格式(使用string.format)进行组合。 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}". 我们的默认格式为“{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. 用户输入12作为所需数据。 When formatting, instead of displaying 2011-0012, it is only displaying 2011-12. 格式化时,它不显示2011-0012,而只显示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)? 我怎样才能确保添加0是没有做一些疯狂的循环,它会附加0或试图解析数字(假设它是一个数字。应该只有足够的0来等于长度为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:0000}” - >用户被迫输入数字时的原始格式。 "{0}-{1:D4}" "{0}-{1:N4}" “{0} - {1:D4}”“”{0} - {1:N4}“

你可以使用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. 您可以使用string.PadLeft添加零,或使用int.TryParse尝试转换为整数。 The latter will double up as your validation check. 后者将作为验证检查加倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM