Java BigDecimal intvalueExact()方法
java.math.BigDecimal.intValueExact() 是一个内置的函数,它可以将这个BigDecimal转换为一个整数值,并检查是否有丢失信息。如果这个BigDecimal有任何小数部分,或者转换的结果太大,无法表示为一个整数值,这个函数会抛出一个算术异常。
语法
public int intValueExact()
参数: 此函数不接受任何参数。
返回值 :该函数返回BigDecimal的整数值。
异常: 如果BigDecimal中存在非零的小数部分,或者它的值过大而不能被表示为整数,该函数会抛出一个ArithmeticException。
例子
Input : "19878124"
Output : 19878124
Input : "721111"
Output : 721111
以下程序说明了java.math.BigDecimal.intValueExact()方法的使用:
程序1 :
// Java program to illustrate
// intValueExact() method
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Creating 2 BigDecimal Objects
BigDecimal b1, b2;
// Assigning values to b1, b2
b1 = new BigDecimal("19878124");
b2 = new BigDecimal("721111");
// Displaying their respective Integer Values
System.out.println("Exact Integer Value of " +
b1 + " is " + b1.intValueExact());
System.out.println("Exact Integer Value of " +
b2 + " is " + b2.intValueExact());
}
}
输出。
Exact Integer Value of 19878124 is 19878124
Exact Integer Value of 721111 is 721111
注意: 与intValue()函数不同的是,当转换的结果太大,无法表示为整数时,该函数会抛弃BigDecimal的任何小数部分,只返回低阶32位,在这种情况下,该函数会抛出算术异常。
程序2: 本程序将说明该函数何时抛出异常。
// Java program to illustrate
// Arithmetic Exception occurrence
// in intValueExact() method
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Creating 2 BigDecimal Objects
BigDecimal b1, b2;
// Assigning values to b1, b2
b1 = new BigDecimal("3232435121868179");
b2 = new BigDecimal("84561789104423214");
// Displaying their respective Integer Values
// using intValue()
System.out.println("Output by intValue() Function");
System.out.println("The Integer Value of " +
b1 + " is " + b1.intValue());
System.out.println("The Integer Value of " +
b2 + " is " + b2.intValue());
// Exception handling
System.out.println("\nOutput by intValueExact() Function");
try {
System.out.println("Exact Integer Value of " +
b1 + " is " + b1.intValueExact());
System.out.println("Exact Integer Value of " +
b2 + " is " + b2.intValueExact());
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught");
}
}
}
输出。
Output by intValue() Function
The Integer Value of 3232435121868179 is -214774381
The Integer Value of 84561789104423214 is -920387282
Output by intValueExact() Function
Arithmetic Exception caught
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValueExact()