Open In App

Java Math signum() Method

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Math.signum() method is a part of the java.lang.Math package. This method returns the sign function of a value passed to it as an argument. In this article, we are going to discuss how this method works for regular values and for special cases such as infinity and NaN.

Special Cases:

  • If the argument is greater than zero, the result will be 1.0.
  • If the argument is equal to zero, the result will be 0.
  • If the argument is less than zero, the result will be -1.0.
  • If the argument is NaN, the result will be NaN.
  • If the argument passed is positive zero or negative zero, then the result will be the same as that of the argument.

These special cases make sure that the signum() methods work correctly.

Syntax of signum() Method

public static double signum(double d)

  • Parameter: This method takes a single parameter d of type double, it is the values whose signum function needs to be calculated.
  • Return Type: This method returns the signum function value of the argument passed to it.

Now, we are going to discuss some examples for better understanding.


Examples of Java Math signum() Method

Example 1: In this example, we will see the basic usage of signum() method.

Java
// Java program to demonstrate the
// working of Math.signum() method
import java.lang.Math;

class Geeks {
    
    public static void main(String args[]) {
        
        // when the argument is greater than zero
        double a = 30;
        System.out.println(Math.signum(a)); 

        // when the argument is equals to zero
        a = 0.0;
        System.out.println(Math.signum(a)); 

        // when the argument is less than zero
        a = -30;
        System.out.println(Math.signum(a));  
    }
}

Output
1.0
0.0
-1.0

Explanation: Here, for a positive number we will get 1.0 and for zero we will get zero and for negative number we will get -1.0 as an output.

Example 2: In this example, we will see how signum() method handles special cases like NaN, positive zero and negative zero.

Java
// Java program to demonstrate handling 
// NaN, positive zero or negative zero
import java.lang.Math; 

public class Geeks {
    
    public static void main(String[] args) {
        
        double nan = Double.NaN;
        double res;

        // Here the argument is NaN
        res = Math.signum(nan);
        System.out.println(res); 

        // Here the argument is positive zero
        res = Math.signum(0.0);
        System.out.println(res);  

        // Here the argument is negative zero
        res = Math.signum(-0.0);
        System.out.println(res);  
    }
}

Output
NaN
0.0
-0.0

Explanation: Here, we are handling the special cases, for NaN we will get NaN and for positive zero we will get 0.0 and for negative zero we will get -0.0


Next Article
Practice Tags :

Similar Reads