Convert list of floats to float array

Hi,

I’m trying to convert a list of floats with elements separated by spaces to an array of floats. I thought this was pretty simple but the following doesn’t seem to fill the array.

float[] data = Array.ConvertAll (ListOfFloats.Split(' '), float.Parse);

What am I doing wrong?

Thanks.

The FormatException is thrown when you pass an empty string to float.Parse. So maybe your input string contains two spaces in a row which would lead to an empty string. You can try this one:

string[] strings = ListOfFloats.Split(new char[]{' '}, System.StringSplitOptions.RemoveEmptyEntries);
float[] data = Array.ConvertAll (strings, float.Parse);

If this still doesn’t help, you may want to further split the code and do the array creation manually

string[] strings = ListOfFloats.Split(new char[]{' '}, System.StringSplitOptions.RemoveEmptyEntries);
float[] data = new float[strings.Length];
for(int i = 0; i < strings.Length; i++)
{
    Debug.Log("i: " + i + " Parsing: >"+strings_+"< ("+strings*.Length+")");*_

data = float.Parse(strings*, System.Globalization.CultureInfo.InvariantCulture);*
}
This will always use the invariant culture (so always use the “.” dot as decimal point). If the string could contain other wrong information like letters of symbols you may want to use [TryParse instead][1]
TryParse will not throw an exception but will simply return false when the conversion fails. The actual value is returned through an out parameter.
[1]: Single.TryParse Method (System) | Microsoft Learn

Thanks. The separator is definitely the space and not the comma. The string is just a list of floats, e.g. “0.22 3.44 2.333”. I have no idea what’s wrong.