Java.math.BigDecimal.longValueExact() 方法



描述

java.math.BigDecimal.longValueExact()將此 BigDecimal 轉換為一個 long 值,並檢查是否存在資訊丟失。如果此 BigDecimal 具有非零小數部分或超出了 long 結果的可能範圍,則會丟擲異常 ArithmeticException。

宣告

以下是 java.math.BigDecimal.longValueExact() 方法的宣告。

public long longValueExact()

引數

返回值

此方法返回 BigDecimal 物件的 long 值。

異常

ArithmeticException− 如果具有非零小數部分或將不適合一個 long 值。

示例

以下示例顯示了 math.BigDecimal.longValueExact() 方法的用法。

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      // create 2 long objecs
      long l1,l2;

      bg1 = new BigDecimal("-429");
      bg2 = new BigDecimal("3.3E+10");

      // assign the long value of bg1 and bg2 to l1,l2 respectively
      l1 = bg1.longValueExact();
      l2 = bg2.longValueExact();

      String str1 = "Exact Long value of " + bg1 + " is " + l1;
      String str2 = "Exact Long value of " + bg2 + " is " + l2;

      // print l1,l2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

讓我們編譯並執行上述程式,這將產生以下結果 −

Exact Long value of -429 is -429
Exact Long value of 3.3E+10 is 33000000000
java_math_bigdecimal.htm
廣告