how to convert String to int or another datatype


This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Richard Siddaway Richard Siddaway 3 years, 7 months ago.

  • Author
  • #11090
    Profile photo of Dominique Hofmann
    Dominique Hofmann

    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
    Profile photo of Dave Wyatt
    Dave Wyatt

    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
    Profile photo of Dominique Hofmann
    Dominique Hofmann

    thank you again again

  • #11100
    Profile photo of Richard Siddaway
    Richard Siddaway

    You can also use the -as operator

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

You must be logged in to reply to this topic.