Freigeben über


How to: Pad a Number with Leading Zeros

Microsoft Silverlight will reach end of support after October 2021. Learn more.

You can pad an integer with leading zeros by using the "D" standard numeric format string together with a precision specifier. You can pad both integer and floating-point numbers with leading zeros by using a custom numeric format string. This topic 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 how many 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.

    1. 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.

    2. 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.

    You can also use the format string in a method, such as Format or 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.

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

outputBlock.FontFamily = New System.Windows.Media.FontFamily("Courier New")

' Display integer values by caling the ToString method.
outputBlock.Text += String.Format("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) & vbCrLf
outputBlock.Text += String.Format("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) & vbCrLf
outputBlock.Text += String.Format("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) & vbCrLf
outputBlock.Text += String.Format("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) & vbCrLf
outputBlock.Text += String.Format("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) & vbCrLf
outputBlock.Text &= vbCrLf

' Display the same integer values by using composite formatting.
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", byteValue) & vbCrLf
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", shortValue) & vbCrLf
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", intValue) & vbCrLf
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", lngValue) & vbCrLf
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", ulngValue) & vbCrLf
' 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
byte byteValue = 254;
short shortValue = 10342;
int intValue = 1023983;
long lngValue = 6985321;
ulong ulngValue = UInt64.MaxValue;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

// Display integer values by caling the ToString method.
outputBlock.Text += String.Format("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) + "\n";
outputBlock.Text += "\n";

// Display the same integer values by using composite formatting.
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", byteValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", shortValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", intValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", lngValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", ulngValue) + "\n";
// 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

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. Formatting it as a decimal value requires that you use the "D" standard format specifier; formatting it as a hexadecimal value requires that you use the "X" standard format specifier.

  3. 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. This defines the total length of the padded string.

  5. 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. 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.

Dim value As Integer = 160934
Dim decimalLength As Integer = value.ToString("D").Length + 5
Dim hexLength As Integer = value.ToString("X").Length + 5

outputBlock.FontFamily = New System.Windows.Media.FontFamily("Courier New")

outputBlock.Text &= value.ToString("D" + decimalLength.ToString()) & vbCrLf
outputBlock.Text &= value.ToString("X" + hexLength.ToString()) & vbCrLf
' The example displays the following output:
'       00000160934
'       00000274A6      
int value = 160934;
int decimalLength = value.ToString("D").Length + 5;
int hexLength = value.ToString("X").Length + 5;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

outputBlock.Text += value.ToString("D" + decimalLength.ToString()) + "\n";
outputBlock.Text += value.ToString("X" + hexLength.ToString()) + "\n";
// 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. Define a custom numeric format string that uses the zero placeholder ("0") to represent the minimum number of zeros.

  3. Call the number's ToString(String) method and pass it the custom format string. You can also use the custom format string with a method that supports composite formatting.

The following example formats several numeric values with leading zeros so that the total length of the formatted number is at least eight digits to the left of the decimal.

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.9321747

outputBlock.FontFamily = New System.Windows.Media.FontFamily("Courier New")

' Display the numbers using the ToString method.
outputBlock.Text &= intValue.ToString(fmt) & vbCrLf
outputBlock.Text &= decValue.ToString(fmt) & vbCrLf
outputBlock.Text &= sngValue.ToString(fmt) & vbCrLf
outputBlock.Text &= sngValue.ToString(fmt) & vbCrLf
outputBlock.Text &= vbCrLf

' Display the numbers using composite formatting.
Dim formatString As String = " {0,15:" + fmt + "}"
outputBlock.Text &= String.Format(formatString, intValue) & vbCrLf
outputBlock.Text &= String.Format(formatString, decValue) & vbCrLf
outputBlock.Text &= String.Format(formatString, sngValue) & vbCrLf
outputBlock.Text &= String.Format(formatString, dblValue) & vbCrLf
' The example displays the following output:
'       01053240
'       00103932.52
'       01549230
'       01549230
'       
'               01053240
'            00103932.52
'               01549230
'          9034521202.93      
string fmt = "00000000.##";
int intValue = 1053240;
decimal decValue = 103932.52m;
float sngValue = 1549230.10873992f;
double dblValue = 9034521202.93217412;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

// Display the numbers using the ToString method.
outputBlock.Text += intValue.ToString(fmt) + "\n";
outputBlock.Text += decValue.ToString(fmt) + "\n";
outputBlock.Text += sngValue.ToString(fmt) + "\n";
outputBlock.Text += sngValue.ToString(fmt) + "\n";
outputBlock.Text += "\n";

// Display the numbers using composite formatting.
string formatString = " {0,15:" + fmt + "}\n";
outputBlock.Text += String.Format(formatString, intValue);
outputBlock.Text += String.Format(formatString, decValue);
outputBlock.Text += String.Format(formatString, sngValue);
outputBlock.Text += String.Format(formatString, dblValue);
// The example displays the following output:
//       01053240
//       00103932.52
//       01549230
//       01549230
//       
//               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. To do this:

    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 does not include a decimal point symbol, determine the string's length.

  3. Create a custom format string that uses the zero placeholder ("0") for each of the leading zeros to appear in the string, and that uses either the zero placeholder or the digit placeholder ("#") to represent each digit in the default string.

  4. Supply the custom format string as a parameter either to the number's ToString(String) method or to a method that supports composite formatting.

The following example pads two Double values with five leading zeros.

outputBlock.FontFamily = New System.Windows.Media.FontFamily("Courier New")

Dim dblValues() As Double = {9034521202.9321747, 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 + "}"

   outputBlock.Text &= dblValue.ToString(fmt) & vbCrLf
   outputBlock.Text &= String.Format(formatString, dblValue) & vbCrLf
Next
' The example displays the following output:
'       000009034521202.93
'         000009034521202.93
'       9034521202
'                 9034521202            
outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");


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 + "}\n";

   outputBlock.Text += dblValue.ToString(fmt) + "\n";
   outputBlock.Text += String.Format(formatString, dblValue);
}
// The example displays the following output:
//       000009034521202.93
//         000009034521202.93
//       9034521202
//                 9034521202