how to convert String to int or another datatype

Tagged: 

This topic contains 3 replies, has 3 voices, and was last updated by  Richard Siddaway 3 years, 9 months ago.

  • Author
    Posts
  • #11090

    Dominique Hofmann
    Participant

    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

    Dave Wyatt
    Moderator

    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

    Dominique Hofmann
    Participant

    thank you again again

  • #11100

    Richard Siddaway
    Moderator

    You can also use the -as operator

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

You must be logged in to reply to this topic.