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:该程序将说明此函数何时引发Exception。
// 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