Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Trying to convert string to float and getting error

Discussion in 'Scripting' started by JimWebs, Sep 25, 2023.

  1. JimWebs

    JimWebs

    Joined:
    Aug 2, 2023
    Posts:
    44
    How do I convert string List element into float? When I try to convert using
    float f = float.Parse(stringtoconvert);
    I get an error input string was not in correct format.

    example,
    mylist {"500","400","300","otherstuff"};
    int element=0;
    var stringtoconvert = (string) mylist[element];
    float f = float.Parse(stringtoconvert);
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    If you cannot guarantee that the input string is in the correct format, you should use TryParse instead.

    Note that depending on locale „1.234“ and „1,234“ may fail to be parsed. I believe you can specify a locale that supports both but can‘t recall from memory what that was. Check the MS docs on TryParse for sure.
     
    PraetorBlue and JimWebs like this.
  3. JimWebs

    JimWebs

    Joined:
    Aug 2, 2023
    Posts:
    44
    Thanks. I got the bug out eventually by testing it through try.
     
  4. JimWebs

    JimWebs

    Joined:
    Aug 2, 2023
    Posts:
    44
    Although I have noticed something which may be a bug. I can't be sure. It seems my List won't update when I change entries. I have to shut down Unity and open it up again for it to work