Powershell - 从数字中删除货币格式

Powershell - remove currency formatting from a number

你能告诉我如何从变量(可能被视为字符串)中删除货币格式吗?

如何从变量中去除货币格式并将其转换为真实数字?

谢谢。

例子

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

但是

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

编程语言 PowerShell 不会 "know" 金钱或货币是什么 - PowerShell 看到的一切都是变量名 (4) 和 属性 引用 (.00) 不存在,所以 $a 最终没有值。

如果您的字符串格式为:[=16=].00,您可以通过编程方式执行的操作是:

# Here is my currency amount
$mySalary = '0.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('()')
}

到目前为止一切顺利,现在我们有了字符串 500.45(如果输入是 (0.45),则为 -500.45)。

现在,您可以执行一些操作来将字符串转换为数字类型。

您可以使用 Parse() 方法将其显式转换为 [double]

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

或者您可以依靠 PowerShell 执行隐式转换为具有一元 +:

的适当数字类型
$mySalaryNumber = +$mySalary