PowerTip: Formatting Numeric Output Using PowerShell


Summary: Learn how to format numeric output in Windows PowerShell by using format specifiers and numeric constants.

Hey, Scripting Guy! Question How can I print the amount of free space on a fixed disk in MB with two decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n2}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)

Hey, Scripting Guy! Question What if I want to display the output in GB with three decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n3}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1GB)

Hey, Scripting Guy! Question I like big numbers. Can I display it in KB and have five decimal places?

Hey, Scripting Guy! Answer Use a format specifier as shown here:

"{0:n5}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB)

Hey, Scripting Guy! Question I want something simple. Can I print the amount of free space on a fixed disk in MB in whole numbers?

Hey, Scripting Guy! Answer No need for a format specifier, as shown here:

[int] ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1MB)


Comments (6)

  1. Anonymous says:

    If there is only a single value to format using ToString(format) is probably clearer than -f (or, its underlying, String.Format):

    So

    "{0:n5}"-f ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB)

    becomes

    ((gwmi win32_logicaldisk -Filter "drivetype='3'").freespace/1KB).ToString("n5")

  2. jrv says:

    Second favorite:

    [System.Convert]::ToString(0x80004005,2)

  3. jrv says:

    I always seem ot get stuck "bit twiddling".  PowerShell makes this a cinch.  No more scientific calculator as PowerShell is my new scientific and programmable calculator.

    Now maybe Mathametica will be ported to PowerShell making PowerShell a super scientific calculator.

  4. jrv says:

    @rjcox – I like that.  It is a very convenient way to grab a reformatted single value.

  5. jrv says:

    This is my favorite:

    0x{0:x}' -f -2147467259

  6. Ed Wilson says:

    @JRV that is cool. I do like it as well — it is also one of my favorites.

Skip to main content