I have a inventory database from my company and I'm wanting to sort some entries based on pricing. I was thinking originally I would have to do everything by hand but I figured Sort-Object should work... until I remembered Sort-Object and its infamous string sorting. Easy, i'll sort by converting it to an integer except of course a currency value has symbol such as $ at the start.
The original code I used which caused the string sorting is below. The classic 200 is higher than 1000 etc:
$Result | Sort-Object -Property Price | Format-Table -Property Price
The int code I tried is:
$Result | Sort-Object -Property { [int]$_.Price } | Format-Table -Property Price
This results in output like "Cannot convert value "$414.50" to type "System.Int32". | Error: "Input string was not in a correct format." Makes sense, cant convert a $ to an int.
So is there any way around this without me having to sort by hand?
Thanks
Firstly, you probably want
[decimal]
instead of[int]
because[int] "414.50"
is414
, not414.50
so you'll be losing precision.That aside, I'm adapting this answer for C#: https://stackoverflow.com/a/56603818/3156906
The advantage of this is that invalid database values like - e.g.
$1.$10
- that might have crept in will throw an exception, as will different currencies like£1.00
so you're getting a bit of extra data validation for free.Note that the results remain as strings, but they're sorted as currency amounts (decimals). If you want the actual numeric value you'll need to convert the values separately...