Java中的 BigDecimal shortValueExact() 方法
Java.math.BigDecimal.shortValueExact()是Java中的一个内置方法,可将此 BigDecimal 转换为短整数,检查丢失的信息。如果此 BigDecimal 有一个非零小数部分或超出可能的范围以产生一个简短的结果,则抛出一个 ArithmeticException。
句法:
public short shortValueExact()
参数:该方法不接受任何参数。
返回值:此方法返回 BigDecimal 对象的短值。
下面的程序说明了上述方法:
方案一:
// Program to demonstrate shortValueExact() method of BigDecimal
import java.math.*;
public class gfg {
public static void main(String[] args)
{
BigDecimal b1 = new BigDecimal("457");
BigDecimal b2 = new BigDecimal("4785");
// Assigning the short value of BigDecimal objects b1 and b2
// to short s1, s2 respectively
short s1 = b1.shortValueExact();
short s2 = b2.shortValueExact();
// Printing s1, s2 values
System.out.println("Exact short value of " + b1 + " is " + s1);
System.out.println("Exact short value of " + b2 + " is " + s2);
}
}
输出:
Exact short value of 457 is 457
Exact short value of 4785 is 4785
方案二:
// Program to demonstrate shortValueExact() method of BigDecimal
import java.math.*;
public class gfg {
public static void main(String[] args)
{
BigDecimal b1 = new BigDecimal("127");
BigDecimal b2 = new BigDecimal("1455");
// assign the short value of BigDecimal objects b1 and b2
// to short s1, s2 respectively
short s1 = b1.shortValueExact();
short s2 = b2.shortValueExact();
// print s1, s2 values
System.out.println("Exact short value of " + b1 + " is " + s1);
System.out.println("Exact short value of " + b2 + " is " + s2);
}
}
输出:
Exact short value of 127 is 127
Exact short value of 1455 is 1455
参考:https: Java/math/BigDecimal.html#shortValueExact()