Check whether a BigDecimal in Java is negative.
You can use the compareTo() method of BigDecimal to determine if the BigDecimal is negative.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal number1 = new BigDecimal("-10.5");
BigDecimal number2 = new BigDecimal("5.5");
System.out.println(isNegative(number1)); // true
System.out.println(isNegative(number2)); // false
}
public static boolean isNegative(BigDecimal number) {
return number.compareTo(BigDecimal.ZERO) < 0;
}
}
In the example above, we defined two BigDecimal objects, number1 and number2, with number1 being a negative number and number2 being a positive number.
Next, we defined a static method isNegative() that takes a BigDecimal as a parameter and compares it to BigDecimal.ZERO using the compareTo() method. If the number is less than 0, it returns true, otherwise it returns false.
Finally, we call the isNegative() method to determine if number1 and number2 are negative, and print the result.