FormatPercent


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 0is 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 Pindicates that we want to format the value as a percentage, and the 1represents the number of digits to display following the decimal point.

 

Got all that? Excellent.

 

The format method is then followed by the –fparameter and the value to be formatted ($a).

 

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

 

11.3 %