Java-math-bigdecimal-bytevalueexact
提供:Dev Guides
Java.math.BigDecimal.byteValueExact()メソッド
説明
- java.math.BigDecimal.byteValueExact()*はBigDecimalをバイトに変換し、失われた情報をチェックします。 このBigDecimalにゼロ以外の小数部分がある場合、またはバイトの結果として可能な範囲外にある場合、ArithmeticExceptionがスローされます。
宣言
以下は、* java.math.BigDecimal.byteValueExact()*メソッドの宣言です。
public byte byteValueExact()
パラメーター
NA
戻り値
このメソッドは、BigDecimalオブジェクトのバイト値を返します。
例外
*ArithmeticException* -BigDecimalオブジェクトにゼロ以外の小数部がある場合、またはバイトに収まらない場合。
例
次の例は、math.BigDecimal.byteValueExact()メソッドの使用法を示しています。
package com.finddevguides;
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