如何:用前导零填充数字How to: Pad a Number with Leading Zeros

通过结合使用“D”标准数字格式字符串和精度说明符,将前导零添加到整数。You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. 你可以通过使用自定义数字格式字符串,将前导零添加到整数和浮点数。You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. 本文介绍如何通过这两种方法用前导零填充数字。This article shows how to use both methods to pad a number with leading zeros.

使用前导零将整数填充到特定的长度To pad an integer with leading zeros to a specific length

  1. 确定整数值要显示的最小位数。Determine the minimum number of digits you want the integer value to display. 在此数字中包括任何前导位。Include any leading digits in this number.

  2. 确定是要将整数显示为十进制值还是十六进制值。Determine whether you want to display the integer as a decimal value or a hexadecimal value.

    • 若要将整数显示为十进制值,则调用其 ToString(String) 方法,并传递字符串“Dn”作为 format 参数的值,其中 n 表示字符串的最小长度 。To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

    • 若要将整数显示为十六进制值,则调用其 ToString(String) 方法,并传递字符串“Xn ”作为 format 参数的值,其中 n 表示字符串的最小长度。To display the integer as a hexadecimal value, call its ToString(String) method and pass the string "Xn" as the value of the format parameter, where n represents the minimum length of the string.

此外,你也可以在 C#Visual Basic 的内插字符串中使用格式字符串,或者可以调用一个 String.FormatConsole.WriteLine 等使用复合格式设置的方法。You can also use the format string in an interpolated string in both C# and Visual Basic, or you can call a method, such as String.Format or Console.WriteLine, that uses composite formatting.

以下示例使用前导零设置若干整数值的格式,以便格式化数字的总长度至少为八个字符。The following example formats several integer values with leading zeros so that the total length of the formatted number is at least eight characters.

byte byteValue = 254;
short shortValue = 10342;
int intValue = 1023983;
long lngValue = 6985321;               
ulong ulngValue = UInt64.MaxValue;

// Display integer values by calling the ToString method.
Console.WriteLine("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8"));
Console.WriteLine("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8"));
Console.WriteLine("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8"));
Console.WriteLine("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8"));
Console.WriteLine("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8"));
Console.WriteLine();

// Display the same integer values by using composite formatting.
Console.WriteLine("{0,22:D8} {0,22:X8}", byteValue);
Console.WriteLine("{0,22:D8} {0,22:X8}", shortValue);
Console.WriteLine("{0,22:D8} {0,22:X8}", intValue);
Console.WriteLine("{0,22:D8} {0,22:X8}", lngValue);
Console.WriteLine("{0,22:D8} {0,22:X8}", ulngValue);
// The example displays the following output:
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//       
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//         18446744073709551615       FFFFFFFFFFFFFFFF
Dim byteValue As Byte = 254
Dim shortValue As Short = 10342
Dim intValue As Integer = 1023983
Dim lngValue As Long = 6985321               
Dim ulngValue As ULong = UInt64.MaxValue

' Display integer values by calling the ToString method.
Console.WriteLine("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8"))
Console.WriteLine("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8"))
Console.WriteLine("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8"))
Console.WriteLine("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8"))
Console.WriteLine("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8"))
Console.WriteLine()

' Display the same integer values by using composite formatting.
Console.WriteLine("{0,22:D8} {0,22:X8}", byteValue)
Console.WriteLine("{0,22:D8} {0,22:X8}", shortValue)
Console.WriteLine("{0,22:D8} {0,22:X8}", intValue)
Console.WriteLine("{0,22:D8} {0,22:X8}", lngValue)
Console.WriteLine("{0,22:D8} {0,22:X8}", ulngValue)
' The example displays the following output:
'                     00000254               000000FE
'                     00010342               00002866
'                     01023983               000F9FEF
'                     06985321               006A9669
'         18446744073709551615       FFFFFFFFFFFFFFFF
'       
'                     00000254               000000FE
'                     00010342               00002866
'                     01023983               000F9FEF
'                     06985321               006A9669
'         18446744073709551615       FFFFFFFFFFFFFFFF

使用特定数目的前导零填充整数To pad an integer with a specific number of leading zeros

  1. 确定希望整数值显示多少个前导零。Determine how many leading zeros you want the integer value to display.

  2. 确定是要将整数显示为十进制值还是十六进制值。Determine whether you want to display the integer as a decimal value or a hexadecimal value.

    • 将其格式设置为十进制值需要使用“D”标准格式说明符。Formatting it as a decimal value requires that you use the "D" standard format specifier.

    • 将其格式设置为十六进制值需要使用“X”标准格式说明符。Formatting it as a hexadecimal value requires that you use the "X" standard format specifier.

  3. 通过调用整数值的 ToString("D").LengthToString("X").Length 方法,确定未填充的数字字符串的长度。Determine the length of the unpadded numeric string by calling the integer value's ToString("D").Length or ToString("X").Length method.

  4. 将你要在格式化字符串中包括的前导零的数目添加到未填充的数字字符串的长度上。Add the number of leading zeros that you want to include in the formatted string to the length of the unpadded numeric string. 添加前导零的个数将定义填充字符串的总长度。Adding the number of leading zeros defines the total length of the padded string.

  5. 调用整数值的 ToString(String) 方法,并且对于十进制字符串传递字符串“Dn ”,对于十六进制字符串传递“Xn ”;其中,n 表示填充的字符串的总长度。Call the integer value's ToString(String) method, and pass the string "Dn" for decimal strings and "Xn" for hexadecimal strings, where n represents the total length of the padded string. 也可以在支持复合格式设置的方法中使用“Dn ”或“Xn ”格式字符串。You can also use the "Dn" or "Xn" format string in a method that supports composite formatting.

下面的示例使用五个前导零来填充整数值。The following example pads an integer value with five leading zeros.

int value = 160934;
int decimalLength = value.ToString("D").Length + 5;
int hexLength = value.ToString("X").Length + 5;
Console.WriteLine(value.ToString("D" + decimalLength.ToString()));
Console.WriteLine(value.ToString("X" + hexLength.ToString()));
// The example displays the following output:
//       00000160934
//       00000274A6      
Dim value As Integer = 160934
Dim decimalLength As Integer = value.ToString("D").Length + 5
Dim hexLength As Integer = value.ToString("X").Length + 5
Console.WriteLine(value.ToString("D" + decimalLength.ToString()))
Console.WriteLine(value.ToString("X" + hexLength.ToString()))
' The example displays the following output:
'       00000160934
'       00000274A6      

使用前导零将数值填充到特定的长度To pad a numeric value with leading zeros to a specific length

  1. 确定数字的字符串表示形式要在小数点的左侧保留的位数。Determine how many digits to the left of the decimal you want the string representation of the number to have. 在此总位数中包括任何前导零。Include any leading zeros in this total number of digits.

  2. 定义一个使用零占位符“0”来表示零的最小数目的自定义数字格式字符串。Define a custom numeric format string that uses the zero placeholder "0" to represent the minimum number of zeros.

  3. 调用数字的 ToString(String) 方法并向其传递自定义格式字符串。Call the number's ToString(String) method and pass it the custom format string. 此外,你也可以将自定义格式字符串与字符串内插或与支持复合格式设置的方法一起使用。You can also use the custom format string with string interpolation or with a method that supports composite formatting.

下面的示例使用前导零设置几个数值的格式。The following example formats several numeric values with leading zeros. 因此,格式化后的数字总长度是小数点左侧至少八位数字。As a result, the total length of the formatted number is at least eight digits to the left of the decimal.

string fmt = "00000000.##";
int intValue = 1053240;
decimal decValue = 103932.52m;
float sngValue = 1549230.10873992f;
double dblValue = 9034521202.93217412;

// Display the numbers using the ToString method.
Console.WriteLine(intValue.ToString(fmt));
Console.WriteLine(decValue.ToString(fmt));           
Console.WriteLine(sngValue.ToString(fmt));
Console.WriteLine(dblValue.ToString(fmt));           
Console.WriteLine();

// Display the numbers using composite formatting.
string formatString = " {0,15:" + fmt + "}";
Console.WriteLine(formatString, intValue);      
Console.WriteLine(formatString, decValue);      
Console.WriteLine(formatString, sngValue);      
Console.WriteLine(formatString, dblValue);      
// The example displays the following output:
//       01053240
//       00103932.52
//       01549230
//       9034521202.93
//       
//               01053240
//            00103932.52
//               01549230
//          9034521202.93      
Dim fmt As String = "00000000.##"
Dim intValue As Integer = 1053240
Dim decValue As Decimal = 103932.52d
Dim sngValue As Single = 1549230.10873992
Dim dblValue As Double = 9034521202.93217412

' Display the numbers using the ToString method.
Console.WriteLine(intValue.ToString(fmt))
Console.WriteLine(decValue.ToString(fmt))            
Console.WriteLine(sngValue.ToString(fmt))
Console.WriteLine(dblValue.ToString(fmt))            
Console.WriteLine()

' Display the numbers using composite formatting.
Dim formatString As String = " {0,15:" + fmt + "}"
Console.WriteLine(formatString, intValue)      
Console.WriteLine(formatString, decValue)      
Console.WriteLine(formatString, sngValue)      
Console.WriteLine(formatString, dblValue)      
' The example displays the following output:
'       01053240
'       00103932.52
'       01549230
'       9034521202.93
'       
'               01053240
'            00103932.52
'               01549230
'          9034521202.93      

使用特定数目的前导零填充数值To pad a numeric value with a specific number of leading zeros

  1. 确定希望数值具有多少个前导零。Determine how many leading zeros you want the numeric value to have.

  2. 确定未填充数字字符串中小数点左侧的位数:Determine the number of digits to the left of the decimal in the unpadded numeric string:

    1. 确定数字的字符串表示形式是否包括小数点符号。Determine whether the string representation of a number includes a decimal point symbol.

    2. 如果它包括小数点符号,则确定小数点左侧的字符数。If it does include a decimal point symbol, determine the number of characters to the left of the decimal point.

      -或--or-

      如果它不包括小数点符号,则确定字符串的长度。If it doesn't include a decimal point symbol, determine the string's length.

  3. 创建使用以下格式的自定义格式字符串:Create a custom format string that uses:

    • 零占位符“0”表示在字符串中出现的每个前导零。The zero placeholder "0" for each of the leading zeros to appear in the string.

    • 零占位符或数字占位符“#”表示默认字符串中的每个数字。Either the zero placeholder or the digit placeholder "#" to represent each digit in the default string.

  4. 将自定义格式字符串作为对数字的 ToString(String) 方法或支持复合格式设置的方法的参数提供。Supply the custom format string as a parameter either to the number's ToString(String) method or to a method that supports composite formatting.

下面的示例使用五个前导零来填充两个 Double 值。The following example pads two Double values with five leading zeros.

double[] dblValues = { 9034521202.93217412, 9034521202 };
foreach (double dblValue in dblValues)
{
   string decSeparator = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
   string fmt, formatString;
   
   if (dblValue.ToString().Contains(decSeparator))
   {
      int digits = dblValue.ToString().IndexOf(decSeparator);
      fmt = new String('0', 5) + new String('#', digits) + ".##";
   }
   else
   {
      fmt = new String('0', dblValue.ToString().Length);   
   }
   formatString = "{0,20:" + fmt + "}";

   Console.WriteLine(dblValue.ToString(fmt));
   Console.WriteLine(formatString, dblValue);
}
// The example displays the following output:
//       000009034521202.93
//         000009034521202.93
//       9034521202
//                 9034521202            
Dim dblValues() As Double = { 9034521202.93217412, 9034521202 }
For Each dblValue As Double In dblValues
   Dim decSeparator As String = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
   Dim fmt, formatString As String
   
   If dblValue.ToString.Contains(decSeparator) Then
      Dim digits As Integer = dblValue.ToString().IndexOf(decSeparator)
      fmt = New String("0"c, 5) + New String("#"c, digits) + ".##"
   Else
      fmt = New String("0"c, dblValue.ToString.Length)   
   End If
   formatString = "{0,20:" + fmt + "}"

   Console.WriteLine(dblValue.ToString(fmt))
   Console.WriteLine(formatString, dblValue)
Next
' The example displays the following output:
'       000009034521202.93
'         000009034521202.93
'       9034521202
'                 9034521202            

请参阅See also