- Java.math 包额外内容
- Java.math - 枚举
- Java.math - 探讨
Java.math.BigDecimal.abs() 方法
描述
java.math.BigDecimal.abs(MathContext mc) 返回一个 BigDecimal,其值是该 BigDecimal 的绝对值,且根据上下文设置进行舍入。
声明
以下是 java.math.BigDecimal.abs() 方法的声明。
public BigDecimal abs(MathContext mc)
参数
mc - 要使用的上下文。
返回值
此方法返回被调用值(即abs(this))的绝对值,根据需要进行舍入。
异常
ArithmeticException - 如果结果不精确,但舍入模式是不必要的。
示例
以下示例展示了 math.BigDecimal.abs() 方法的用法。
package com.tutorialspoint;
import java.math.*;
public class BigDecimalDemo {
public static void main(String[] args) {
// create 3 BigDecimal objects
BigDecimal bg1, bg2, bg3;
MathContext mc = new MathContext(2);
MathContext mc1 = new MathContext(4);
// assign value to bg1
bg1 = new BigDecimal("40.1234");
// assign absolute value of bg1 to bg2 rounded to 2 precision using mc
bg2 = bg1.abs(mc);
// assign absolute value of bg1 to bg3 rounded to 4 precision using mc1
bg3 = bg1.abs(mc1);
String str1,str2;
str1 = "Absolute value, rounded to 2 precision is " + bg2;
str2 = "Absolute value, rounded to 4 precision is " + bg3;
// print bg2 and bg3 value
System.out.println( str1 );
System.out.println( str2 );
}
}
让我们编译并运行以上的程序,它会产生以下结果 -
Absolute value, rounded to 2 precision is 40 Absolute value, rounded to 4 precision is 40.12
java_math_bigdecimal.htm
广告