Search code examples
stringunity-game-enginefloating-pointtype-conversionrotation

Convert string to float without loosing decimal places


I am having lots of strings that represent rotation values. These strings have 0 to 5 decimal places.

When converting these strings to floats to apply them as rotation values to GameObjects, the float value is always cut short to 4 decimal places. With more than 500 GameObjects, this will result in a huge imprecision over time.

How can I preserve all decimal places?

This is the code I used [modified for better understanding]:

myString = "344.93873";
segment.transform.rotation = Quaternion.Euler((float)double.Parse(myString), 0f, 0f);

What I get is 344.9387 without the 3 at the end. The loss happens here: (float)double.

However, when manually rotating objects in Unity3D, I can see rotation values with more than 4 decimal places in the Inspector.


Solution

  • Per default float.ToString

    The ToString() method formats a Single value in the default ("G", or general) format of the current culture.

    And further per default for float (=Single)

    Single
    Smallest round-trippable number of digits to represent the number (in .NET Framework, G7 is the default)

    Now your input number

    344.93873
    

    has 8 digits so per default it is clamped to

    344.9387
    

    which has only 7 digits.

    A float can have ~6-9 digits so in order to be sure to always see the full value you should use

    print(myFloat.ToString("G9"));
    

    Besides that: Yes indeed have in mind that either way floating point numbers have a limited precision.

    It is very much possible that the exact value of

    344.93873
    

    is not representable using a float!

    See .Net fiddle

    double.Parse() => 344.93873000000002093656803481280803680419921875
    float.Parse => 344.938720703125
    

    Tbh honest though in your use case of angles. There is no way whatsoever, not even in nature anyone will notice a difference of a 0.00001° angle!

    Have in mind that after all Unity is a realtime 3D "Game"-Engine which on purpose drops precision in favor for a faster runtime.