Log in

No account? Create an account
entries friends calendar profile Elf Sternberg's Pendorwright Projects Previous Previous Next Next
The Number Formatting Commands in Powershell - Elf M. Sternberg
The Number Formatting Commands in Powershell

I don’t have much experience with Windows, but I have to work in it for ${EMPLOYER} now and then.  I had this weird problem today where the output of a PowerShell script was pre-formatted, but the consumer of that output (namely, a Splunk server) wanted raw numbers.  To force raw numbers on output, PowerShell provides the Format CmdLet.

Now, I really don’t like PowerShell.  It has all the syntax of Perl, all the sensibility of Smalltalk, and all the verbosity of Donald Trump.  But if the client wants it, that’s what you work with.  I did Perl for six years and Smalltalk for two, so PowerShell is rather easy for me.  It’s just knowing what’s available in the library that’s hard, like number format commands.

The Format CmdLet is an in-line operation activated with the -f command.  Its operations have the syntax {0:C}.. For example:

$money = "Total paid: {0:C}" -f $paid

All objects in PowerShell are arrays of some kind. The zero in the snippet {0:C} means “use the first (zeroeth) item”, which is almost always what you want. The “C” indicates that we’re going to use currency. Which currency symbol will be used depends upon your localization settings. The letter may be followed by a number in some cases; this translates to different things (leading zeros for integers, for example; precision for fixed-point reals).

And that’s it. The CmdLet supports the following formatting translations: “C”: Currency; “D”: Decimal; “E”: Exponential; “F”: Fixed Point; “G”: General; “N”: Number; “P”: Percentages; “R”: Round-Trip, a number that precisely matches the format of its input with special considerations for culture-specific notation; “X”: Hexadecimal.

More can be found at MSDN Standard Numeric Format Strings.

In a lot of ways, these look like Python’s old numeric formatting operations.  If you’re familiar with those, these should be straightforward.  It’s just a slightly different syntax, like everything Microsoft does.  I think it’s an attempt by Microsoft to crowd out the open source alternatives by cognitive overload.

Leave a comment