Java BigDecimal toBigIntegerExact()方法
java.math.BigDecimal.toBigIntegerExact() 是java中的一个内置方法,用于将这个BigDecimal转换为BigInteger,并检查是否有丢失的信息。如果这个BigDecimal有一个非零的小数部分,就会产生一个异常。
语法
public BigInteger toBigIntegerExact()
参数: 该方法不接受任何参数。
返回值: 该方法返回BigDecimal对象转换为BigInteger的值。
举例说明
Input: (BigDecimal) 1213
输出: (BigInteger) 1213
Input: (BigDecimal) 12785412
输出: (BigInteger) 12785412
下面的程序说明了上述方法的工作:
程序1
// Program to demonstrate toBigIntegerExact() method of BigDecimal
import java.math.*;
public class gfg {
public static void main(String[] args)
{
// Assigning BigDecimal b
BigDecimal b = new BigDecimal("1213");
// Assigning the BigIntegerExact value of BigInteger b to BigInteger i
BigInteger i = b.toBigIntegerExact();
// Printing i value
System.out.println("BigInteger value of " + b + " is " + i);
}
}
输出。
BigInteger value of 1213 is 1213
程序2
// Program to demonstrate toBigIntegerExact() method of BigDecimal
import java.math.*;
public class gfg {
public static void main(String[] args)
{
// Assigning BigDecimal b
BigDecimal b = new BigDecimal("12785412");
// Assigning the BigIntegerExact value of BigInteger b to BigInteger i
BigInteger i = b.toBigIntegerExact();
// Printing i value
System.out.println("BigInteger value of " + b + " is " + i);
}
}
输出。
BigInteger value of 12785412 is 12785412