Converting VBScript's FormatPercent Function

Windows PowerShell

Definition: Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.


In Windows PowerShell you can format a value as a percent by using the .NET formatting methods. For example, these two commands set the value of $a to .113, then use .NET formatting to format $a as a percentage:

$a = .113
$a = "{0:P1}" -f $a

The formatting command is interpreted like this: you specify the format type in brackets - {} - with the entire method (brackets and all) enclosed in double quote marks. The 0 is the index number of the item to be formatted (in this case it’s a 0 because we're dealing with a single string value). The P indicates that we want to format the value as a percentage, and the 1 represents the number of digits to display following the decimal point.

Got all that? Excellent.

The format method is then followed by the -f parameter and the value to be formatted ($a).

When you run this command and then echo back the value of $a you should get the following:

11.3 %

Return to the VBScript to Windows PowerShell home page