-4

So I have created a simple script where, I have a float variable "rps", which starts off at 0.001.

Every second I add 0.0001 to this variable.

When I output the variable to the screen in Unity 3D, why does it come out as a really long decimal, like 0.001099999999?

So instead of adding 0.0001 it adds 0.00009999999999, when that is 100% not what I am adding.

Is there anyway to fix this, or is it just a bug within Unity or C#, if I am unable to fix it, is there an easy way to round it, as I have searched the internet, and it all looks like a lot of code, that doesn't seem necessary. Thanks for any help

Technivorous
  • 1,682
  • 2
  • 16
  • 22
  • Possible duplicate of [C# float magically changing value](https://stackoverflow.com/questions/4542575/c-sharp-float-magically-changing-value) – Ruzihm Oct 24 '18 at 20:47
  • Unity doesn't use C++. It uses C#. – Ruzihm Oct 24 '18 at 20:47
  • @Ruzihm thanks for guiding me to the duplicte, did not see that one, and sorry about accidentally putting it as C++, been using a lot of C++ for robotics recently –  Oct 24 '18 at 20:49
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – brady Oct 24 '18 at 20:49

2 Answers2

1

try this:

float rounded = (float)(Math.Round((double)f, 4);

you will need to adjust it a little but you should get the idea.

Technivorous
  • 1,682
  • 2
  • 16
  • 22
0

used fixed point or integers if you need that level of precision.

float precision = 10000f; // 1.0000
int rps = (int)(0.001f * precision); // or rps = 10
int inc = (int)(0.0001f * precision); // or inc = 1

while (...)
{
    rps += inc;

    float rps_as_float = rps / precision;
}
DangerMouse
  • 110
  • 3