Formatting Percentages

Microsoft® Windows® 2000 Scripting Guide

Sometimes raw numbers are not as meaningful as percentages. For example, event logs have a maximum size that can vary from computer to computer. Because of that, simply knowing the current size of an event log (a property that can be retrieved by using WMI) will not tell you whether the log is nearly full and should be backed up and cleared. In this case, it might be more useful to know the maximum allowed size (another property available through WMI) as well as the current size. This lets you determine what percentage of the event log is "full" and what percentage is still available.

If you are going to retrieve numbers as percentages, it is a good idea to also report those numbers as percentages. For example, suppose you have an event log with a maximum size of 5,000,000 bytes and a current size of 3,127,354 bytes. To determine how full the event log is, you can divide 3,127,354 by 5,000,000. When you do the calculation, the value .6254708 is returned. To lessen the possibility of confusion, it is better to have this value returned as a percentage (63%).

The FormatPercent function converts a number to a percentage; in effect, this means multiplying the number by 100 and then appending a percent symbol. However, FormatPercent also accepts the same optional parameters as FormatNumber. These parameters allow you to:

  • Specify the number of digits to be displayed after the decimal point.

  • Place a leading 0 in front of fractional values (numbers less than 1 but greater than 0).

  • Display negative values in parentheses.

  • Group digits using a group separator (allowing you to display a value as 6,500,000% rather than 6500000%).

The syntax for the FormatPercent function is identical to that for FormatNumber: You supply the value to be formatted, followed by zero or more parameters. As with FormatNumber, the order in which the parameters are presented is crucial. For example, the leading 0 must always be the second parameter following the value being formatted. If you do not want to specify a value for the first parameter (number of digits following the decimal point), use False as a placeholder for that parameter.

The following script divides 1 by 7 and echoes the result. The script then uses FormatPercent to display the result as a percentage, with no decimal places.

Const NoDecimals = 0
NumberToFormat = 1 / 7
Wscript.Echo NumberToFormat
Wscript.Echo FormatPercent(NumberToFormat, NoDecimals)

When the preceding script is run under CScript, the following output appears in the command window: