Why sometimes float 0.1f + float 0.1f = 0.2000001f ?

Sometimes if I do:

float num1 = 0.1f;
float num2 = 0.1f;

float result = num1 + num2;

Debug.Log(result);

The result is 0.2000001

Why?

because it’s a floating point number, it’s never gonna be entirely accurate.

The way they are encoded means that not all numbers may be perfectly represented, and that will get you small, incremental errors, just as you’ve noticed.

I advise taking the time to read through Floating-point arithmetic - Wikipedia for a detailled explanation, but the takeaway is this:

  • don’t rely on the precision of arithmetic operation on floats
  • don’t compare floats by equality ( sqrt(0.1*0.1) may not be equal to 0.1 ), be tolerant to small differences
  • the further you are from 0.0, the bigger the errors will be. IIRC, around 10K you may get as much as a 0.1 error.

You can use Mathf.Approximately to compare equality on floating point numbers.