Even though this post has an answer already, the answer does not handle negative values indicated by either ()
or -
. Since this is the question that pops up when googling how to parse a currency string into a decimal value in PowerShell, I figured I would leave an update.
For brevity in the code examples, I am using the enum int value directly rather than the enum name.
[System.Globalization.NumberStyles]
Instead of 383
, you should really be using:
[System.Globalization.NumberStyles]::Currency
Using [decimal]::TryParse()
- method returns bool indicating status of parsing attempt, if successful, method returns $True
and the reference variable is populated with the parsed value, otherwise the method returns $False
and the reference variable is set to 0.
New-Variable -Name test -Force
$null = [decimal]::TryParse('-$ 1,200.20' , 383, (Get-Culture).NumberFormat, [ref]$test); $test
$null = [decimal]::TryParse('($ 1,200.20)', 383, (Get-Culture).NumberFormat, [ref]$test); $test
$null = [decimal]::TryParse('$1,200.20' , 383, (Get-Culture).NumberFormat, [ref]$test); $test
$null = [decimal]::TryParse('$1200.20' , 383, (Get-Culture).NumberFormat, [ref]$test); $test
$null = [decimal]::TryParse('$ 1200.2' , 383, (Get-Culture).NumberFormat, [ref]$test); $test
$null = [decimal]::TryParse('$1200' , 383, (Get-Culture).NumberFormat, [ref]$test); $test
Using [decimal]::Parse()
- Either is successful, or throws an exception.
[decimal]::Parse('-$ 1,200.20' , 383, (Get-Culture).NumberFormat) # Returns '-1200.20'
[decimal]::Parse('($ 1,200.20)', 383, (Get-Culture).NumberFormat) # Returns '-1200.20'
[decimal]::Parse('$(1,200.20)' , 383, (Get-Culture).NumberFormat) # Returns '-1200.20'
[decimal]::Parse('$1,200.20' , 383, (Get-Culture).NumberFormat) # Returns '1200.20'
[decimal]::Parse('$1200.20' , 383, (Get-Culture).NumberFormat) # Returns '1200.20'
[decimal]::Parse('$ 1200.2' , 383, (Get-Culture).NumberFormat) # Returns '1200.2'
[decimal]::Parse('$1200' , 383, (Get-Culture).NumberFormat) # Returns '1200'
This answer was adapated from a similar answer for C#:
Convert currency string to decimal?
Just a tip to future readers, if you can't find the answer to what you need under the PowerShell tag, try searching under C# / .NET. You'll likely be able to find the answer there, and then you can adapt the answer to use in PowerShell, which is how I came up with this answer.