-3

I made a test in C# with unity3d engine.

like this:

float dt = 22.05f + 0.05f;

dt value should be 22.1f but i debug dt value in VS2015,dt value is 22.0999985f. I don't know why it was not the correct value I expected.

Paweł Marecki
  • 632
  • 1
  • 9
  • 19
  • That is the correct value with floats. See this: http://stackoverflow.com/questions/618535/difference-between-decimal-float-and-double-in-net – bit Mar 25 '16 at 09:50
  • http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary – CodeCaster Mar 25 '16 at 09:56

1 Answers1

0

Because floats are binary - you can not express every decimal number exactly. Not on the fraction side, where it has to be constructed out of parts that are binary: 1/2, 1/4, 1/8 etc.

.1 (1/10th) can only be approximated.

This leads to all kinds of small issues that programmers - mostly those who refuse to learn programming by reading books that explain things in detail - fall into.

Another item is that you should not never ever compare floats to a constant - if the float is calculated, it may be SLIGHTLY off. You always compare whether the difference between two values is smaller than a given small epsilon (Abs(a-b)

TomTom
  • 1
  • 9
  • 78
  • 143