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 Reading csv files with periods(float) not working

Discussion in 'Scripting' started by Tornado77, Jul 20, 2020.

  1. Tornado77

    Tornado77

    Joined:
    Nov 14, 2018
    Posts:
    83
    Hi, I'm trying to import a .csv which contain floats, but Unity seems to have some trouble reading it. When I import a simple .csv sheet with integers only, everything works fine. But when I import the same sheet with floats instead of integers, I get the error:FormatException: Input string was not in a correct format. Is there any way to fix this?
    EDIT: After some experiments, I realized that my script failed to reed line 3, which contains a minus, but line 1 and 2 are fine.
    upload_2020-7-19_19-13-35.png
    upload_2020-7-19_19-14-59.png
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    Have you tried printing out the exact string it's choking on? That would help a great deal in diagnosing this issue.

    Also inspecting the raw CSV file in a plain text editor might be revealing too.
     
    Suddoha likes this.
  3. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    It's probably the (current) culture that is used by the parse method which appears to expect a different separator, most-likely a comma. You either need to change the separator for the purposes of formatting, or supply a format provider that supports dots.

    If that's not the issue, you need to do some more testing.
     
  4. Tornado77

    Tornado77

    Joined:
    Nov 14, 2018
    Posts:
    83
    I just did it, in the plain text editor it looks like this
    upload_2020-7-19_19-30-52.png
    Its not the same sheet, but its the same kind of values with the same number of rows.
    When I print it:
    upload_2020-7-19_19-31-39.png
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,723
    I just tried parsing that exact string:
    Code (CSharp):
    1. Debug.Log(float.Parse("-0.494323"));
    This worked completely fine for me. I think @Suddoha is probably correct about the culture being the issue. You may be using a culture that is expecting a comma to denote the decimal point. So maybe try something like this:
    Code (CSharp):
    1. float.Parse(components[1], CultureInfo.InvariantCulture);
    This is good practice anyway because your code could otherwise break based simply on the user's device settings.
     
  6. Tornado77

    Tornado77

    Joined:
    Nov 14, 2018
    Posts:
    83
    It's working! Thank you so much!