How to: Pad a Number with Leading Zeros

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

' Display integer values by caling 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
byte byteValue = 254;
short shortValue = 10342;
int intValue = 1023983;
long lngValue = 6985321;               
ulong ulngValue = UInt64.MaxValue;

// Display integer values by caling 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

To pad an integer with a particular 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
Console.WriteLine(value.ToString("D" + decimalLength.ToString()))
Console.WriteLine(value.ToString("X" + hexLength.ToString()))
' 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;
Console.WriteLine(value.ToString("D" + decimalLength.ToString()));
Console.WriteLine(value.ToString("X" + hexLength.ToString()));
// The example displays the following output: 
//       00000160934 
//       00000274A6      

To pad any numeric value with leading zeros to a specific length

  1. Determine how many digits to the left of the decimal that 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.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(sngValue.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 
'       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;

// Display the numbers using the ToString method.
Console.WriteLine(intValue.ToString(fmt));
Console.WriteLine(decValue.ToString(fmt));           
Console.WriteLine(sngValue.ToString(fmt));
Console.WriteLine(sngValue.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 
//       01549230 
//        
//               01053240 
//            00103932.52 
//               01549230 
//          9034521202.93      

To pad any numeric value with a particular 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 its left.

    3. 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 of the digits present 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.

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

See Also

Concepts

Custom Numeric Format Strings

Standard Numeric Format Strings

Composite Formatting

Change History

Date

History

Reason

October 2008

Added the topic.

Information enhancement.