In Java, Math.signum(d) returns the sign of a number: -1.0 if it is negative, 1.0 if it is positive, and zero if it is zero.
It answers "which direction?" without caring "how far?". That makes it handy for trends (up or down), movement toward a target one step at a time, and turning a difference into a simple direction.
A static method of the java.lang.Math class, added in Java 5 (JDK 1.5). Call it on the class name, as in Math.signum(...). No import is needed, because classes in java.lang are always visible.
Syntax
Pass a double or a float; the result has the same type.
There is no int overload. An int argument widens to float, so cast the result back with (int). Integer.signum(int) is an integer-only alternative that returns an int.
Library declarations
Java
// java.lang.Math
public static double signum(double d)
public static float signum(float f)
Parameters
Parameter
Description
d / f
The number whose sign you want.
Return Value
Return Value
Description
double / float
-1.0 for negative input, 1.0 for positive input, the argument itself for 0.0, -0.0, and NaN.
Only the direction survives. A rise of 2.75 and a rise of 0.01 would both give 1.0; the size of the change is thrown away.
Three possible results. -0.5 gives -1.0 and 0.0 gives 0.0, so a simple pair of comparisons picks the right word.
Double output. The sign values print as 1.0, -1.0, and 0.0 because signum(double) returns a double.
Example 2 — Move One Step at a Time Toward a Target
A game piece walks along a line until it reaches its target, one square per move.
Java
public class MathSignumStep {
public static void main(String[] args) {
int position = 2;
int target = -1;
while (position != target) {
position += (int) Math.signum(target - position);
System.out.println("moved to " + position);
}
}
}
Output
moved to 1
moved to 0
moved to -1
How It Works
Difference to direction.target - position is -3; its sign, -1, says "move left" no matter how far away the target is.
int widens to float. There is no signum(int), so Java calls signum(float); the (int) cast turns -1.0f back into the step -1.
Stops exactly. Each move shrinks the distance by one, so after three moves position equals target and the loop ends.
Example 3 — Negative Zero, NaN, Infinity, and float