Java.math.BigDecimal.byteValueExact() 方法



說明

java.math.BigDecimal.byteValueExact() 將 BigDecimal 轉換為一個位元組,檢查丟失的資訊。如果此 BigDecimal 帶有非零小數部分或超出位元組結果的可能範圍,則丟擲 ArithmeticException。

宣告

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

public byte byteValueExact()

引數

不適用

返回值

此方法返回 BigDecimal 物件的位元組值。

異常

ArithmeticException - 如果 BigDecimal 物件帶有一個非零小數部分,或者無法容納在一個位元組內。

示例

以下示例展示了 math.BigDecimal.byteValueExact() 方法的使用方式。

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      // Create 2 byte objects
      byte i1, i2;

      // assign values to bg1 and bg2
      bg1 = new BigDecimal("-128");
      bg2 = new BigDecimal("48");

      // any BigDecimal value greater than 127 or less than -128,
      // will generate exception as it doesn't fit in byte range

      // this	method also generates exception for decimal values like 12.10

      // assign the byte value of bg1 and bg2 to i1,i2 respectively
      i1 = bg1.byteValueExact();
      i2 = bg2.byteValueExact();

      String str1 = "Exact byte value of " + bg1 + " is " + i1;
      String str2 = "Exact byte value of " + bg2 + " is " + i2;

      // print i1,i2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

讓我們編譯並執行上面的程式,它將產生以下結果 -

Exact byte value of -128 is -128
Exact byte value of 48 is 48
java_math_bigdecimal.htm
廣告