vxs*_*122 5 string powershell currency
有没有办法将货币字符串转换为浮动值,例如:
$1,138.15
$ 29.10
$2,195.34
Run Code Online (Sandbox Code Playgroud)
应转换为:
1138.15
29.10
2195.34
Run Code Online (Sandbox Code Playgroud)
某些货币字符串在美元符号和美元价值之间有空格.
我这样做是因为我从PDF中提取成本值(转换为txt文件)并对它们进行算术运算.例如,文本文件的一部分如下所示:
Fixed Power
$1,138.15
General Admin Surcharge
$ 29.10
Customer Charge
$2,195.34
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样:
$sourceFile = Get-Content $sourcePath\$($filenames[0]).txt
$fixedPower = $sourceFile[(
Select-String `
-Path $sourcePath\$($filenames[0]).txt `
-Pattern "Fixed Power" `
-List
).LineNumber + 1]
$generalAdminSurcharge = $sourceFile[(
Select-String `
-Path $sourcePath\$($filenames[0]).txt `
-Pattern "General Admin Surcharge" `
-List
).LineNumber + 1]
$customerCharge = $sourceFile[(
Select-String `
-Path $sourcePath\$($filenames[0]).txt `
-Pattern "Customer Charge" `
-List
).LineNumber + 1]
Run Code Online (Sandbox Code Playgroud)
但那些只将成本提取到字符串值中.
$Test = '$1,138.15','$ 29.10','$2,195.34'
$Test |
foreach { $_ -replace '[^0-9.]'}
1138.15
29.10
2195.34
Run Code Online (Sandbox Code Playgroud)
如果你想要尾随0,你必须将它保留为[string],直到你想要进行计算.
您可以执行替换操作以删除字符串中您想要删除的所有多余内容,然后将其转换为 [decimal]
[decimal]$customerCharge = $customerCharge -replace "(\$| |,)"
Run Code Online (Sandbox Code Playgroud)
编辑:粗略的mjolinor击败了我,并且做得更好。伙计,他很好!