Java BigDecimal longValueExact()方法
java.math.BigDecimal.longValueExact() 是一个内置的函数,它可以将这个BigDecimal转换为一个长值,并检查丢失的信息。如果这个BigDecimal有任何小数部分,或者转换的结果太大,无法表示为一个长值,这个函数会抛出算术异常。
语法
public long longValueExact()
参数: 此函数不接受任何参数。
返回值 :该函数返回BigDecimal的长值。
异常: 如果BigDecimal中存在非零的小数部分,或者其值过大而不能被表示为长值,则该函数会抛出ArithmeticException。
例子
Input : "1987812456121"
Output : 1987812456121
Input : "721111"
Output : 721111
以下程序说明了java.math.BigDecimal.longValueExact()方法的使用:
程序1 :
// Java program to illustrate
// longValueExact() 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("267694723232");
b2 = new BigDecimal("721111845617");
// Displaying their respective Long Values
System.out.println("Exact Long Value of " +
b1 + " is " + b1.longValueExact());
System.out.println("Exact Long Value of " +
b2 + " is " + b2.longValueExact());
}
}
输出。
Exact Long Value of 267694723232 is 267694723232
Exact Long Value of 721111845617 is 721111845617
注意: 与longValue()函数不同的是,当转换的结果太大,无法表示为长值时,该函数会抛弃BigDecimal的任何小数部分,只返回低阶64位,在这种情况下,该函数会抛出算术异常。
程序2 :
// Java program to illustrate
// Arithmetic Exception occurrence
// in longValueExact() 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("267694723232435121868");
b2 = new BigDecimal("72111184561789104423");
// Displaying their respective Long Values
// using longValue()
System.out.println("Output by longValue() Function");
System.out.println("The Long Value of " + b1 + " is " + b1.longValue());
System.out.println("The Long Value of " + b2 + " is " + b2.longValue());
// Exception handling
System.out.println("\nOutput by longValueExact() Function");
try {
System.out.println("Exact Long Value of " +
b1 + " is " + b1.longValueExact());
System.out.println("Exact Long Value of " +
b2 + " is " + b2.longValueExact());
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught");
}
}
}
输出。
Output by longValue() Function
The Long Value of 267694723232435121868 is -9006437873208152372
The Long Value of 72111184561789104423 is -1675791733049102041
Output by longValueExact() Function
Arithmetic Exception caught
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#longValueExact()