C# 将整数转换为三位数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10832567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert integer number to three digit
提问by user1270940
I have an integer variable .if its 1-9 it only displays as "1" or "9", I'm looking to convert the variable to save as 3 digits, ie. "001", or "009", etc. any ideas? I am using C#,ASP.Net
我有一个整数变量。如果它的 1-9 它只显示为“1”或“9”,我希望将变量转换为 3 位数字,即。“001”或“009”等任何想法?我正在使用 C#,ASP.Net
采纳答案by Yahia
回答by Jürgen Steinblock
What about
关于什么
var result = String.Format("{0:000}", X);
var result2 = X.ToString("000");
回答by Kishore Kumar
int i = 5;
string retVal = i.ToString().PadLeft(3, '0');
回答by Mohan Gopi
int i = 5;
string tVal=i.ToString("000");
回答by MCollard
来自:https: //docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#DFormatString
The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative.
“D”(或十进制)格式说明符将数字转换为一串十进制数字 (0-9),如果数字为负,则以减号为前缀。
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
精度说明符指示结果字符串中所需的最小位数。如果需要,数字在其左侧填充零以生成精度说明符给出的位数。
Like:
喜欢:
int value;
value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345
value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345

