Contact

Subscribe via Email

Subscribe via RSS/JSON

Categories

Recent Posts

Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

Elsewhere

Format-Table FormatString

In the previous post I wanted to convert some output to percentage figures and resorted to type casting to get it done. Turns out I don’t need to do that. Was reading more about the Format-Table cmdlet and saw that the hash table that supplies calculated properties also supports a key called FormatString which let’s one specify the format of the output.

For a quick overview of FormatString read this MSDN page. You can see various format specifier strings mentioned there. These let you define the format of the output.

Say I want to see the current time and output the remaining minutes to the hour as a percentage.

I can get the current minute thus:

I can use an Expression block to show the balance minutes:

And if I want to format the output such that it’s shown as a percentage (the value multiplied by 100 with a % sign suffixed) I can use FormatString with the “P” format specifier:

This gives the output as a percentage figure with two decimal places (the default). I can modify that by suffixing a number to the “P” specifying the desired number of decimal places. Like for instance:

If I want to round, I can use the “r” specifier. I can do decimal, scientific, fixed point, and so on.

Returning to the code of the previous post, here’s a revised version:

There’s two changes: (1) I don’t type cast the Capacity to [uint32] any more to round it, rather I use the “F0” format specifier which stands for a fixed-point number with 0 decimal digits (i.e. a number like 42.9517669677734 gets converted to 43); (2) I don’t type cast for the free space to percentage either, I just use the “P1” format specifier which stands for a percentage figure with 1 decimal digit (i.e. a number like 48.6%).

Neat!

Format-Table FormatString by rakhesh is licensed under a Creative Commons Attribution 4.0 International License.