Quantcast
Channel: Tachytelic.net
Viewing all articles
Browse latest Browse all 210

How to add Thousands separators to a number with Powershell

$
0
0

When working with long numbers, they are much easier to read with the thousand separators included. The Powershell format operator makes it simple.

$Number = 2109999.86
'{0:N0}' -f $Number
'{0:N2}' -f $Number

Produces the following output:

As you can see from the above, the first example produces a whole number with no decimal places, and the second one includes two decimal places.

In practice, when I needed to do this, the number provided to me was actually a string read from a CSV File, so although you can use the format operator, it won’t do anything:

Image showing Powershell trying to add thousand separators to a number stored as a string.

The string needs to be cast as a number before you can use the format operator in this way:

$StringNumber = "10456.21" 
$($StringNumber -as [decimal]).ToString('N2')

Produces a number with separators:

You can use the format operator for all sorts of things. You might like this post on how to format leading zeros with the format operator.

The post How to add Thousands separators to a number with Powershell appeared first on Tachytelic.net.


Viewing all articles
Browse latest Browse all 210

Trending Articles