What is Math.signum in Java?

What is the signum function?

Any real number has a magnitude and a sign associated with it. A real number’s sign, also known as the signum, is -1 for negative numbersnumbers with a minus sign, 0 for zero, or +1 for positive numbersnumbers with a plus sign.

Return type

The signum() method in the Math class in Java works as follows:

  1. Returns 1 if the number passed is greater than zero.

  2. Returns 0 if the number passed is equal to zero.

  3. Returns -1 if the number passed is less than zero.

  4. Returns NaN if the number passed is NaNNot a Number.

Method signature

public static double signum(double d)

Parameters

double d: the value whose signum is to be returned.

Overloaded methods

  1. public static double signum(double d)

  2. public static float signum(float f)

Code

In the code below, we calculate the signum for four different values with the help of the signum() function.

public class Main {
public static void main(String[] args) {
System.out.println("Signum for -1000 is " + Math.signum(-1000));
System.out.println("Signum for 0 is " + Math.signum(0));
System.out.println("Signum for 1000 is " + Math.signum(1000));
System.out.println("Signum for NaN is " + Math.signum(Double.NaN));
}
}