[英]How to format int into a string with leading Zeros and Commas
我需要将一个int转换为一个长度为9位+ 2个逗号的字符串。
1将成为000,000,001
12345将成为000,012,345
等等
我知道我可以使用ToString()。PadLeft(...)添加前导零但不知道如何添加逗号而不使用一些if测试。 有没有更有效的方法来做到这一点?
只是使用:
int myint = 12345;
string formatted = myint.ToString("000,000,000");
int number = 12345;
String result = String.Format("{0:000,000,000}", number);
你可以使用自定义字符串格式,这将是简单的,但可能不是很有效,因为手卷特定格式的代码:
string text = value.ToString("000,000,000", CultureInfo.InvariantCulture);
请注意使用CultureInfo.InvariantCulture
来避免使用当前线程的文化分组字符(和数字)。
手动滚动的一个选择:
static string ToDigitsAndCommas(int value)
{
char[] chars = new char[11];
chars[3] = ',';
chars[7] = ',';
int remainder;
for (int i = 0; i < 9; i++)
{
value = Math.DivRem(value, 10, out remainder);
chars[10 - i - (i / 3)] = (char) (remainder + '0');
}
return new string(chars);
}
我建议对此进行基准测试,以确定您是否真的需要它而不是更简单的代码:)
只需在ToString()
使用格式说明符:
var stringified = yourNumber.ToString("000,000,000");
你会得到零填充的逗号。
使用ToString()并将结果格式指定为参数。
有关详细信息,请参阅MSDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.