how to convert String to int or another datatype

Welcome Forums General PowerShell Q&A how to convert String to int or another datatype

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
5 years, 1 month ago.

  • Author
    Posts
  • #11090

    Participant
    Points: 0
    Rank: Member

    Hello together
    my question is how can i convert an variable $Size (content in attachment) from String to another datatype like integer or string

  • #11095

    Member
    Points: 0
    Rank: Member

    We can't tell from that screenshot exactly what type $Size was; it could have been either String, Double, or Decimal. Based on your other thread, I would guess it was Double.

    There are different ways of converting variables to other types. Which one you choose depends mainly on how you want to handle errors, and if you're willing to accept an automatic loss of precision. For example, here are some different ways you might try to attempt to convert the value 2.9055827878416 to an Integer (which cannot contain a decimal portion):

    $double = [double]2.9055827878416
    
    [int]$double  # Results in integer 2.  The decimal portion of the double is simply discarded (not rounded)
    [int][math]::Floor($double)  # Same as above.
    [int]::Parse($double)  # This produces an error, because the double value (which is implicitly casted to a string first) contains a decimal portion.
    [int][math]::Round($double)  # Results in integer 3, since we rounded the value up to 3.0 as a Double first.
    
  • #11099

    Participant
    Points: 0
    Rank: Member

    thank you again again

  • #11100

    Participant
    Points: 0
    Rank: Member

    You can also use the -as operator

    $a = "122"
    $b = $a -as [int]

The topic ‘how to convert String to int or another datatype’ is closed to new replies.