Java BigDecimal toBigInteger()方法
java.math.BigDecimal.toBigInteger() 是java中一个内置的方法,可以将这个BigDecimal转换为BigInteger。这种转换类似于从双数到长数的缩小原始转换。这个BigDecimal的任何小数部分都将被丢弃。这种转换会丢失关于BigDecimal值的精度信息。
注意: 如果在不精确转换中出现异常(换句话说,如果一个非零的小数部分被丢弃),请使用toBigIntegerExact()方法。
语法
public BigInteger toBigInteger()
参数: 该方法不接受任何参数。
返回值: 该方法返回BigDecimal对象转换为BigInteger的值。
举例说明
输入: (BigDecimal) 123.321
输出: (BigInteger) 123
输入: (BigDecimal) 123.001
输出: (BigInteger) 123
以下程序说明了上述方法的工作。
程序1 :
// Program to demonstrate toBigInteger() method of BigDecimal
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Assigning the BigDecimal b
BigDecimal b = new BigDecimal("123.321");
// Assigning the BigInteger value of BigDecimal b to BigInteger i
BigInteger i = b.toBigInteger();
// Print i value
System.out.println("BigInteger value of " + b + " is " + i);
}
}
输出
BigInteger value of 123.321 is 123
程序2
// Program to demonstrate toBigInteger() method of BigDecimal
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Assigning the BigDecimal b
BigDecimal b = new BigDecimal("123.001");
// Assigning the BigInteger value of BigDecimal b to BigInteger i
BigInteger i = b.toBigInteger();
// Printing i value
System.out.println("BigInteger value of " + b + " is " + i);
}
}
输出
BigInteger value of 123.001 is 123
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toBigInteger()