2

I'm learning PowerShell in school, I have a basic question regarding percentage calculations:

$foo = "10%"
$bar = "5%"
$foo -gt $bar
False

I tried converting to integer type:

[int]$foo -gt [int]$bar
Cannot convert value "10%" to type "System.Int32". 
Error: "Input string was not in a correct format."

Is there a percentage data type in PowerShell? Or a comparison operator for working with percentages?

user9924807
  • 707
  • 5
  • 22
  • 1
    No and no. PowerShell can *format* percentages by using the .NET formatting facilities (e.g. `(0.5).ToString("0%")`) but it cannot parse them (and neither can the .NET formatting facilities). There are (rather elaborate) [workarounds](https://stackoverflow.com/q/2171615/4137916) on the .NET level, but for PowerShell it's perhaps simplest to just remove the percent and parse (i.e. `[double] ("10%" -replace "%", "")`, even though this may not be strictly correct for all cultures. – Jeroen Mostert Sep 10 '18 at 10:59

1 Answers1

5

Not really, but you can trim them to quickly extract the integer part:

PS> [int]$foo.trim('%') -gt [int]$bar.trim('%')
True
mklement0
  • 382,024
  • 64
  • 607
  • 775
kabanus
  • 24,623
  • 6
  • 41
  • 74