gpt4 book ai didi

string - 如何将货币字符串转换为数值?

转载 作者:行者123 更新时间:2023-12-02 03:17:16 25 4
gpt4 key购买 nike

有没有办法将货币字符串转换为 float 值,例如:

$1,138.15
$ 29.10
$2,195.34

应转换为:

1138.15
29.10
2195.34

某些货币字符串在美元符号和美元值之间有空格。

我这样做是因为我从 PDF(转换为 txt 文件)中提取成本值并对它们进行算术运算。例如,文本文件的一部分如下所示:

Fixed Power

$1,138.15

General Admin Surcharge

$ 29.10

Customer Charge

$2,195.34

我的代码如下所示:

$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]

但这些仅将成本提取为字符串值。

最佳答案

$Test = '$1,138.15','$ 29.10','$2,195.34'

$Test |
foreach { $_ -replace '[^0-9.]'}


1138.15
29.10
2195.34

如果你想要尾随 0,你必须将其保留为 [string],直到你用它进行任何你想要的计算。

关于string - 如何将货币字符串转换为数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24830167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com