Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Powershell how can I convert a string with a trailing 'sign' to a number?

I need to convert strings with optional trailing signs into actual numbers using Powershell.

Possible strings are:

  • 1000-
  • 323+
  • 456

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.

like image 310
Rob Paterson Avatar asked Nov 18 '08 23:11

Rob Paterson


People also ask

How do I convert a string to a number in 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.

How do I convert string to decimal in PowerShell?

[decimal]$string. Replace(",", ".")

How do you convert decimal to integer in PowerShell?

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.


3 Answers

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);
like image 98
Jim Burger Avatar answered Nov 06 '22 19:11

Jim Burger


[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
like image 36
Peter Seale Avatar answered Nov 06 '22 19:11

Peter Seale


Here's a better way to get the enum values:

$type = [System.Globalization.NumberStyles]
[enum]::GetValues($type)
like image 23
halr9000 Avatar answered Nov 06 '22 18:11

halr9000