0 out of 2 rated this helpful - Rate this topic

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

    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.


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


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


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


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            


Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Third sample recoded in PowerShell
<#
.SYNOPSIS
Shows formatting of double values.
.DESCRIPTION
This script, a re-implementation of an MSDN Sample,
creates a double value then formats it with 5 leading
zeros.
.NOTES
File Name : Show-NumberPadding3.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://pshscripts.blogspot.com/
MSDN sample posted to:
http://msdn.microsoft.com/en-us/library/dd260048.aspx
.EXAMPLE
Psh> Show-NumberPadding3.ps1
01053240
00103932.52
01549230

01053240
00103932.52
01549230
9034521202.93

#>

$fmt = "00000000.##"
[int] $intValue = 1053240
[decimal] $decValue = 103932.52
[float] $sngValue = 1549230.10873992
[double] $dblValue = 9034521202.93217412

# Display the numbers using the ToString method
$intValue.ToString($fmt)
$decValue.ToString($fmt)
$sngValue.ToString($fmt)
""

# Display the numbers using composite formatting
$formatString = " {0,15:" + $fmt + "}" # right justified
$formatString -f $intValue
$formatString -f $decValue
$formatString -f $sngValue
$formatString -f $dblValue
Padding a number - Sample using PowerShell
<#
.SYNOPSIS
Shows formatting of leading Zeros
.DESCRIPTION
This script, a re-implementation of an MSDN Sample,
creates several numbers of varying type, then
displays them using .NET Formatting. The second set
of formatting shows the difference between .ToString()
and composite format strings to format - to approaches
that accomplish the same goal!
.NOTES
File Name : Show-NumberPadding1.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN sample posted to:
http://msdn.microsoft.com/en-us/library.
.EXAMPLE
Psh> Show-NumberPadding1.ps1
00000254 000000FE
00010342 00002866
01023983 000F9FEF
06985321 006A9669
9223372036854775807 7FFFFFFFFFFFFFFF
18446744073709551615 FFFFFFFFFFFFFFFF

00000254 000000FE
00010342 00002866
01023983 000F9FEF
9223372036854775807 7FFFFFFFFFFFFFFF
18446744073709551615 FFFFFFFFFFFFFFFF

#>

[byte] $byteValue = 254
[int16] $shortValue = 10342
[int] $intValue = 1023983
[long] $lngValue = 6985321
[long] $lngValue2 = [System.int64]::MaxValue
[UInt64] $ulngValue = [System.UInt64]::MaxValue

# Display integer values by caling the ToString method.
"{0,22} {1,22}" -f $byteValue.ToString("D8"), $byteValue.ToString("X8")
"{0,22} {1,22}" -f $shortValue.ToString("D8"), $shortValue.ToString("X8")
"{0,22} {1,22}" -f $intValue.ToString("D8"), $intValue.ToString("X8")
"{0,22} {1,22}" -f $lngValue.ToString("D8"), $lngValue.ToString("X8")
"{0,22} {1,22}" -f $lngValue2.ToString("D8"), $lngValue2.ToString("X8")
"{0,22} {1,22}" -f $ulngValue.ToString("D8"), $ulngValue.ToString("X8")
""

# Display the same integer values by using composite formatting
"{0,22:D8} {0,22:X8}" -f $byteValue
"{0,22:D8} {0,22:X8}" -f $shortValue
"{0,22:D8} {0,22:X8}" -f $intValue
"{0,22:D8} {0,22:X8}" -f $lngValue2
"{0,22:D8} {0,22:X8}" -f $ulngValue
Sample 2 - recoded in PowerShell
<#
.SYNOPSIS
Shows formatting of leading Zeros for integers.
.DESCRIPTION
This script, a re-implementation of an MSDN Sample,
creates a value then diplays it using Decimal and Hex
format strings.
.NOTES
File Name : Show-NumberPadding2.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://pshscripts.blogspot.com/
MSDN sample posted to:
http://msdn.microsoft.com/en-us/library/dd260048.aspx
.EXAMPLE
Psh> Show-NumberPadding2.ps1
00000160934
00000274A6

#>
# Create values
[int] $value = 160934
[int] $decimalLength = $value.ToString("D").Length + 5
[int] $hexLength = $value.ToString("X").Length + 5

# Display using ToString()
$value.ToString("D" + $decimalLength.ToString())
$value.ToString("X" + $hexLength.ToString())
Please re-write this help topic so it makes sense

It should not take 500 lines to explain this topic.   Add a simple example with String.Format instead of talking around the subject.