none
Powershell: Why is the Toint32() Method of a String Object always fails? RRS feed

  • Question

  • Hey,

    I have a String object in Powershell, and I want to convert this into a integer. I could see that Object in String class do have Toint32() method provided, and I suppose I should call this one to convert this into a integer, but I always fails. 

    PS C:\windows\system32> $number="12345"
    PS C:\windows\system32> $number.gettype().fullname
    System.String

    PS C:\windows\system32> $number.Toint32()
    Cannot find an overload for "Toint32" and the argument count: "0".
    At line:1 char:1
    + $number.Toint32()
    + ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    What is the right way to call this method? 

    Thanks,

    Jesse

    Thursday, June 25, 2015 7:29 AM

All replies

  • Jesse,

    This one isn't very intuitive.  .ToInt32() is looking for information on how you format your numbers--where you put your commas, etc.  If you don't give it a format definition, it will use the default definition on your computer.  But the trick is to know how to not give it a definition in such a way that it understands that you aren't giving it one.

    Try this:

    $Number = "12345"

    $Number.ToInt32( $Null )


    Tim Curwick
    MadWithPowerShell.com

    Thursday, June 25, 2015 7:42 PM
  • Hello, 

    Alternatively, you can cast your variable to a int this way :

    [int]number = $number

    Thursday, July 18, 2019 11:53 AM
  • Sorry Michael,

    [int]number = $number

    results in

    Unexpected token "number = $number" in expression or statement.

        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken
     

    [int]$i = $number also does not work.

    Sunday, November 10, 2019 6:37 PM
  • Sorry Michael,

    [int]number = $number

    results in

    Unexpected [...]

    This can't work, because the dollar sign on the left is missing. It have to be

    [int]$number=$number
    [int]$i = $number also does not work.

    This should work. If it doesn't, your variable may not be stringtype. What does the output of

    $number.gettype()
    look like?



    • Edited by TK1987 Monday, November 11, 2019 8:51 AM
    Monday, November 11, 2019 8:35 AM