Is there a way to convert currency strings to floating values, for example:
$1,138.15
$ 29.10
$2,195.34
Should be converted to:
1138.15
29.10
2195.34
Some currency strings have space between the dollar sign and the dollar value.
I am doing this because I am extracting the cost values from PDFs (which are converted to txt files) and do arithmetic on them. For example, a portion of text file looks like this:
Fixed Power
$1,138.15
General Admin Surcharge
$ 29.10
Customer Charge
$2,195.34
And my code looks like this:
$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]
But those only extract the costs into string values.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System.Convert class.
Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.
We will be using . LabelEncoder() from sklearn library to convert categorical data to numerical data. We will use function fit_transform() in the process.
Let's see a Python program to convert the currency of one country to that of another country. To use this service, one must need the API key, which can be get from here. We will use fixer API to get the live conversion rates and convert the corresponding amount.
$Test = '$1,138.15','$ 29.10','$2,195.34'
$Test |
foreach { $_ -replace '[^0-9.]'}
1138.15
29.10
2195.34
If you want the trailing 0 you'll have to leave it as [string] until you do whaterver calculations you want with it.
You could do a Replace to remove whatever extra things you want gone from the string, and then cast it as a [decimal]
[decimal]$customerCharge = $customerCharge -replace "(\$| |,)"
Edit: Of coarse mjolinor beat me to it, and did it better. Man he's good!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With