📜  Java中的 BigDecimal longValueExact() 方法

📅  最后修改于: 2022-05-13 01:55:51.993000             🧑  作者: Mango

Java中的 BigDecimal longValueExact() 方法

Java.math.BigDecimal.longValueExact()是一个内置函数,可将此BigDecimal 转换为 long 值并检查丢失的信息。如果BigDecimal 有任何小数部分或转换结果太大而无法表示为 long 值,则此函数将引发算术异常。

句法:

public long longValueExact()

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

返回值:此函数返回BigDecimal 的 long 值。

异常:如果BigDecimal 中有非零小数部分或其值太大而无法表示为 long,则该函数将引发ArithmeticException

例子:

Input : "1987812456121"
Output : 1987812456121

Input : "721111"
Output : 721111

下面的程序说明了Java.math.BigDecimal.longValueExact() 方法的使用:
方案一:

// 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 的任何小数部分,并且当转换结果太大而无法表示为 long 值时仅返回低位 64 位,此函数在这种情况下抛出算术异常.

方案二:

// 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: Java/math/BigDecimal.html#longValueExact()