當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BigDecimal longValueExact()用法及代碼示例


java.math.BigDecimal.longValueExact()是一個內置函數,該函數將該BigDecimal轉換為long值並檢查丟失的信息。如果此BigDecimal的任何小數部分或轉換的結果太大而無法表示為一個long值,則此函數將引發算術異常。

用法:

public long longValueExact()

參數:該函數不接受任何參數。


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

異常:如果此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的任何小數部分並在轉換結果太大而無法將其表示為long值時僅返回低階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()



相關用法


注:本文由純淨天空篩選整理自RICHIK BHATTACHARJEE大神的英文原創作品 BigDecimal longValueExact() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。