Powershell-从数字中删除货币格式 [英] Powershell - remove currency formatting from a number

查看:99
本文介绍了Powershell-从数字中删除货币格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您告诉我如何从变量(可能被视为字符串)中删除货币格式。

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?

谢谢。

示例

PS C:\Users\abc> $a=($464.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
($464.00)                 <- this works


推荐答案

PowerShell是一种编程语言,无法知道货币是什么-PowerShell所看到的只是一个变量名( $ 464 )和不存在的属性引用( .00 ),因此 $ a 最终没有价值

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.

如果您使用以下形式的字符串: $ 00.00 ,则可以通过编程方式执行以下操作:

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('()')
}

到目前为止,到目前为止,我们已经有了字符串 500.45 (如果输入为($ 500.45),则为 -500.45 )。

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.

您可以使用 Parse()<明确将其转换为 [double] / code>方法:

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

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

或者您可以依靠PowerShell将隐式转换为一元 +

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

$mySalaryNumber = +$mySalary

这篇关于Powershell-从数字中删除货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆