PowerShell: How to Pad Number with Leading Zeros


You can use the following syntax in PowerShell to pad a number with a specific number of leading zeros:

'{0:d6}' -f [int]$my_variable

This particular example adds enough leading zeros to the number stored in the variable named $my_variable so that the number has a total length of 6.

Note that we use the -f operator to ‘format’ the variable in a specific manner and we use [int] to first cast the variable to an integer in case it is currently stored as a string.

Feel free to change 6 to a different number to instead pad the number to a different length.

The following example shows how to use this syntax to pad a number with leading zeros in practice.

Example: How to Pad Number with Leading Zeros in PowerShell

Suppose that we a variable named $my_variable in PowerShell that contains the following number:

  • 548

Suppose that we would like to pad this variable with enough leading zeros that it has a length of 6.

We can use the following syntax to do so:

$my_variable = 548
'{0:d6}' -f [int]$my_variable 

The following screenshot shows how to use this syntax in practice:

PowerShell pad number with leading zeros

Notice that enough leading zeros have been added to the number so that it has a total length of 6:

  • 000548

Note that this syntax would still work if our number happened to be stored as a string instead.

For example, suppose the variable had a value stored as ‘548’ instead:

$my_variable = '548'
'{0:d6}' -f [int]$my_variable 

The following screenshot shows how to use this syntax in practice:

PowerShell pad string with leading zeros

Since we used the [int] command to first cast our variable to an integer, we were able to successfully pad the value with leading zeros without receiving any errors.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Remove Leading Zeros
PowerShell: How to Trim Leading Spaces from String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Extract Only Numbers from String

Leave a Reply