Powershell - remove currency formatting from a number

最后都变了- 提交于 2019-12-14 03:16:30

问题


can you please tell me how to remove currency formatting from a variable (which is probably treated as a string).

How do I strip out currency formatting from a variable and convert it to a true number?

Thank you.

example

PS C:\Users\abc> $a=($464.00)
PS C:\Users\abc> "{0:N2}" -f $a
                         <- returns blank

However

PS C:\Users\abc> $a=-464
PS C:\Users\abc> "{0:C2}" -f $a
($464.00)                 <- this works

回答1:


PowerShell, the programming language, does not "know" what money or currency is - everything PowerShell sees is a variable name ($464) and a property reference (.00) that doesn't exist, so $a ends up with no value.

If you have a string in the form: $00.00, what you can do programmatically is:

# Here is my currency amount
$mySalary = '$500.45'

# Remove anything that's not either a dot (`.`), a digit, or parentheses:
$mySalary = $mySalary -replace '[^\d\.\(\)]'

# Check if input string has parentheses around it
if($mySalary -match '^\(.*\)$')
{
    # remove the parentheses and add a `-` instead
    $mySalary = '-' + $mySalary.Trim('()')
}

So far so good, now we have the string 500.45 (or -500.45 if input was ($500.45)).

Now, there's a couple of things you can do to convert a string to a numerical type.

You could explicitly convert it to a [double] with the Parse() method:

$mySalaryNumber = [double]::Parse($mySalary)

Or you could rely on PowerShell performing an implicit conversion to an appropriate numerical type with a unary +:

$mySalaryNumber = +$mySalary


来源:https://stackoverflow.com/questions/38484818/powershell-remove-currency-formatting-from-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!