I need to convert strings with optional trailing signs into actual numbers using Powershell.
Possible strings are:
I'm trying to use System.Int.TryParse with a NumberStyles of AllowTrailingSign, but I can't work out how to make System.Globalization.NumberStyles available to Powershell.
Use [int] to Convert String to Integer in PowerShell The data type of $a is an integer . But when you enclose the value with " " , the data type will become string . To convert such string data type to integer, you can use [int] as shown below.
[decimal]$string. Replace(",", ".")
The easiest way to do this in Powershell is, using the [int] accelerator. Look at the below example for more clarity. Another way available is to use the System. Math dotnet class which has functions to adjust a decimal to nearest integer.
EDIT: as per Halr9000's suggestion
$foo = "300-";
$bar = 0;
$numberStyles = [System.Globalization.NumberStyles];
$cultureInfo = [System.Globalization.CultureInfo];
[int]::TryParse($foo, $numberStyles::AllowTrailingSign, $cultureInfo::CurrentCulture, [ref]$bar);
[System.Globalization.NumberStyles]::AllowTrailingSign
I should also point out, that when I'm dealing with enums in general, sometimes I can get by typing a string. E.g. in this case, just put
"AllowTrailingSign"
Final note, when quizzing an Enum for all possible values, use the line:
[System.Globalization.NumberStyles] | gm -static
Here's a better way to get the enum values:
$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
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