Mathf.Sign(0) not returning zero

Viewed 417

Why does Mathf.Sign(0) return one in Unity? According to the C# documentation, it should return zero.

Mathf.Sign(0.3); // 1
Mathf.Sign(-0.3); // -1
Mathf.Sign(0); // 1, expected 0
2 Answers

The Unity Mathf.Sign has it's own behavior. To get the expected behavior, use the standard C# Math.Sign instead.

If you look into the Mathf source code you find

public static float Sign(float f) { return f >= 0F ? 1F : -1F; }

as also mentioned in the API

Return value is 1 when f is positive or zero, -1 when f is negative.

they indeed explicitly skip the 0 value and this always returns 1 or -1.


As also already mentioned by Magnesium you should use System.Math.Sign if you want the 0 behavior.


Or actually for using float rather than double right away you could probably use System.MathF.Sign as well

Related