Java中的BigDecimal intvalueExact()方法

这个 JAVA数学大十进制。intValueExact() 是一个内置函数,用于转换 将BigDecimal设置为整数值,并检查丢失的信息。如果此BigDecimal有任何小数部分,或者转换结果太大而无法表示为整数值,则此函数会引发算术异常。

null

语法:

public int intValueExact()

参数: 此函数不接受任何参数。

返回值: 此函数返回 大十进制。

例外情况: 函数抛出一个 算术异常 如果这个BigDecimal中有一个非零的小数部分,或者它的值太大,无法表示为整数。

例如:

Input : "19878124"
Output : 19878124

Input : "721111"
Output : 721111

下面的程序演示了java的使用。数学大十进制。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,当转换结果太大而无法表示为整数值时,此函数将抛出 算术异常 在这种情况下。

项目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( "Output 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()

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享