Floating number won't sum up

The _amount member never changes in that simple script. Any good reason for that?

using UnityEngine;

public class WeirdFloat : MonoBehaviour
{
    float _amount = 540000f;
   
    void Update()
    {
        _amount += 0.01f;
        
        Debug.Log($"_amount: {_amount}");
    }
}

Yes, that’s normal. It is the floating point precision errors and it is how floating point numbers are represented in computers see: https://en.wikipedia.org/wiki/Floating-point_arithmetic and https://en.wikipedia.org/wiki/Single-precision_floating-point_format.

4 Likes

Everything that meredoth notes above is 100%, plus here’s some options:

Use a double instead, down-converting it when you need it.

Use an int or long and consider +1 equal to +0.01 and then divide everything by 100f before display or computation with other values. This is called fixed point.

4 Likes

Exactly. For those who don’t like reading (which is great btw, you should try it sometimes) there’s this great Computerphile video by Tom Scott which explains how floating point numbers work and what the issues are.

1 Like

Also, be aware that the statement above involves a float conversion to string, which can truncate decimal places. What you see in the string may not be precisely what is stored in the float.

There are options to control how the conversion works, though:

2 Likes