Strange result of float in Android

Hi Guys,

Doing something really simple. Comparing two floats between each other on Android. The result is confuddling me a little.

Got a simple script here that converts the string into a float, and then checks that float against another float.

Here’s the script:

private static bool CheckElevationtoGL(string str)
    {
        if (Debug.isDebugBuild)
        {
            CDSDebug.Log("TextChecker::CheckElevationtoGL() - Checking against string " + str + ". Actual result is " + FireData.QE_FOR_RANGE);
        }

        bool bComplete = false;

        float elevation;
        if (ConvertToFloat(str, out elevation))
        {
            float difference = elevation - FireData.QE_FOR_RANGE;

            if (Debug.isDebugBuild)
            {
                CDSDebug.Log("TextChecker::CheckElevationtoGL() - ConvertToFloat() completed. Output is " + elevation + ". Difference is " + difference);
            }

            if (difference <= 0)
            {
                bComplete = true;

                if (Debug.isDebugBuild)
                {
                    CDSDebug.Log("TextChecker::CheckElevationtoGL() - Correct input. bComplete is " + bComplete);
                }
            }
        }
        return bComplete;
    }

And here’s the output:

TextChecker::SetElevationtoGL() - Checking against string 849.4. Actual result is 849.4
TextChecker::SetElevationtoGL() - ConvertToFloat() completed. Output is 849.4. Difference is 6.103516E-05

So you can see why it’s returning false. Can anyone shed some light on why it’s throwing this strange output? FireData.QE_FOR_RANGE is just a standard float:

public static float QE_FOR_RANGE = 0;

Just for reference. This works totally okay in the editor. It only fluffs up on device.

What is your convert to float method?
6.103516E-05 is basically 0, but due to floating point imprecision your convert method is giving you that weird value.
I think that weird number is your androids epsilon

I think the epsilon is different for different computers.
I am not sure why it works on your computer and not the android. Maybe your computer is just handling the float differently.

When comparing floats, use Mathf.Approximately.

1 Like

Boom, worked perfectly! Thanks :slight_smile: …Yeah I’m not sure why the errors throwing itself up, but I’m glad I know about it now.

1 Like