C# 整数的字符串格式
我有一个包含两个字符串的类,一个反映当前年份,另一个表示某个值。这些字段根据用户指定的格式(使用 string.format)进行组合。重要提示:用户输入的数据通常是生成的,因此它始终是整数,我们不必担心这一点。
我们的默认格式是“{0}-{1:000}”。然而,现在用户指定的数据是一个字符串,它不希望进行适当的格式化。下面是一个示例:
用户输入 12 作为所需数据。格式化时,不显示2011-0012,只显示2011-12。我怎样才能确保添加 0,而不进行一些疯狂的循环来附加 0 或尝试解析数字(假设它是一个数字。应该只有足够的 0 来等于长度为 4 的字符串)?
这是我尝试过的格式:
“{0}-{1:0000}”->当用户被迫输入数字时的原始格式。 “{0}-{1:D4}” “{0}-{1:N4}”
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}"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
string.PadLeft()
:You could use
string.PadLeft()
:您可以使用 string.PadLeft 在左侧添加零,或使用 int.TryParse 尝试转换为整数。后者将作为您的验证检查加倍。
You can use
string.PadLeft
to add the zeros to the left, or useint.TryParse
to attempt conversion to an integer. The latter will double up as your validation check.