How to convert negative numbers to positive numbers in BigDecimal in Java?
In Java, you can use the abs() method to convert the value of a BigDecimal object to a positive number. An example is shown below:
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal number = new BigDecimal("-123.45");
// 使用abs()方法将负数转为正数
BigDecimal positiveNumber = number.abs();
System.out.println("原始值:" + number);
System.out.println("转换为正数:" + positiveNumber);
}
}
In the example above, we created a BigDecimal object ‘number’ with a value of -123.45. We then used the abs() method to convert it into a positive number and stored the result in ‘positiveNumber’. Finally, we printed out the original value and the converted positive value. The result is as follows:
原始值:-123.45
转换为正数:123.45