What is the BigDecimal.signum() method in Java?

BigDecimal is an immutable, arbitrary-precision signed decimal number. It contains an arbitrary precision integer unscaled value and a 32-bit integer scale. For example, in the value 10.11, 1011 is the unscaled value, and 2 is the scale. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Read more about the BigDecimal class here.

The signum method of the BigDecimal class retrieves the signum function of a BigDecimal value.

Syntax

public int signum()

Parameters

This method does not take any arguments.

Return value

This method returns:

  • 1 if the value of BiDecimal is greater than zero.

  • -1 if the value of BiDecimal is less than zero.

  • 0 if the value of BiDecimal is equal to zero.

Code

The example below demonstrates how to use the signum method.

import java.math.BigDecimal;
class BigDecimalRemainderExample {
public static void main( String args[] ) {
BigDecimal val1 = new BigDecimal("10.10");
BigDecimal val2 = new BigDecimal("-10.10");
BigDecimal val3 = new BigDecimal("0.0");
System.out.println("Signum of " + val1 + " :"+ val1.signum());
System.out.println("Signum of " + val2 + " : "+ val2.signum());
System.out.println("Signum of " + val3 + " : "+ val3.signum());
}
}

Explanation

In the above code:

  • We imported the BigDecimal class.

  • We created three BigDecimal objects, val1 with a value of 10.10, val2 with a value of -10.10, and val3 with a value of 0.0.

  • We called the signum method on the created BigDeciaml objects.

    • For the val1 object, we get 1 as the result because val1 > 0.
    • For the val2 object, we get -1 as the result because val2 < 0.
    • For the val3 object, we get 0 as the result because val3 = 0.

Free Resources