- Home /
Is it a good idea to check if a float isn't zero
As I understand floats can't be checked for equality - but is it different with the 0?
Is it a good idea to use
float a=0;
if(a!=0) DoSomething();
Or should I use
float a=0;
if(a>0 || a<0) DoSomething();
instead. Or is there no difference?
Can I check a float for equality with zero? Can it somehow go wrong, so that it reads 0.000001 instead of 0 and the if becomes true?
This is because my game character has stats as floats, but I want them written in UI only if they are not 0. Or should I simply compare it with an arbitrary, really small value?
Answer by DaDonik · Jan 22, 2015 at 11:46 AM
This is how you should do it, or better said how you can do it safely.
public bool FloatIsZero(float _fValue, float _fEpsilon)
{
bool bRet = false;
if ((_fValue < _fEpsilon) && (_fValue > -_fEpsilon))
{
bRet = true;
}
return bRet;
}
Thanks! The $$anonymous$$athf class thingy turns out have the epsilon - this means I don't need to give it as a parameter right?
Yup, either remove the epsilon parameter and use $$anonymous$$athf.Epsilon inside the function, or just pass $$anonymous$$athf.Epsilon to the function. I do it the second way, because i can change it, depending on how exactly i want to check for any given purpose.
Answer by Owen-Reynolds · Jan 22, 2015 at 08:10 PM
It depends.
If you are doing something which you know will eventually set it to zero, than checking ==0
is fine. For example, in x=Mathf.Clamp(x,0,100);
if x is -14, it will be set to exactly 0. It will never, ever turn -14 into 0.0000001.
And in x=Mathf.MoveTowards(x,0,Time.deltaTime);
you will end at exactly 0. If you know x starts positive, then checking x<=0
is a nice reminder. But if you aren't sure whether x starts positive or negative, while(x!=0)
works fine.
In other words, anything which set x=0
will not add "rounding error," and if(x==0)
is safe.
If you have an equation, which should hit 0, that's when rounding happens. Starting from 10 and subtracting 0.1 over and over may hit 0.000001 instead of 0. Or a rigidbody at -1 moving at a speed of 0.1 may skip 0 and hit 0.000001 instead.
Answer by Studio-JD · Jan 22, 2015 at 12:03 PM
Or you can use it :
if(!Mathf.Approximately(a, 0f)) DoSomething();
Didn't even know that function exists...
Still i like having a variable epsilon parameter, in case i have to 'finetune' it.