Can you correctly convert string to float for WebGL?

Hi everyone,

I have a problem while converting string to float in WebGL build :

public string myString = "3.124";
public float myFloat;

float.TryParse(myString, out myFloat);

Debug.Log(myFloat);

In Unity Editor and Windows Build, myFloat return the correct value : 3.124
But in WebGL, the point is replaced by a comma and myFloat become 3,124 which is 3124

I read that parsing float depends on globalization (I’m in France, with French OS environment) and I tried to work with the following arguments :

float.Parse(myString, System.Globalization.CultureInfo.InvariantCulture.NumberFormat)

Unfortunately it does not work…

Here is a screenshot of the Firefox console debug :


1. is the Debug.Log of the float (result of parse float) (with a comma, not a point, the original string is “3.581”)
2. is the interpreted value (my float is used for positionning a gameobject with Vector3, here is the Debug.Log of transform.position)

Does anyone have the solution ?
Thank you !

This is pretty clearly a bug and you probably should report it via the bugreporter.

If you need a suboptimal solution now you could create a custom function along the lines of something like this:

float ParseString(string input)
    {
        int pos = input.IndexOf(".");
        if(pos < 0) return float.Parse(input);
        int power = input.Length - pos - 1;

        float value = float.Parse(input.Remove(pos, 1));
        float divideBy = Mathf.Pow(10, power);

        return value / divideBy;
    }

Thank you, I suspected that it was a bug, I will report it.
I will try the solution you suggest, I’ll see if it works.

1 Like

Utilise CultureInfo.InvariantCulture , pas CultureInfo.InvariantCulture.NumberFormat

ou encore https://discussions.unity.com/t/419201/6

J 'ai eu le même probleme il y a pas mal de temps.

2 Likes

Effectivement ça fonctionne parfaitement, un grand merci ! C’était tout con en fait :slight_smile:

Problem solved : float.Parse(myString, System.Globalization.CultureInfo.InvariantCulture) is working perfectly !