Java BigDecimal byteValueExact()方法
java.math.BigDecimal.byteValueExact() 是一个内置的函数,可以将BigDecimal转换为字节,并检查是否丢失了信息。任何大于127或小于-128的BigDecimal值都会产生一个异常,因为它不适合在字节范围内。
语法
public byte byteValueExact()
参数: 该方法不接受任何参数。
返回值: 本方法返回BigDecimal对象的字节值。
异常: 如果BigDecimal有一个非零的小数部分,也就是一个十进制的数值,或者超出了一个字节结果的可能范围,该函数会抛出ArithmeticException。
例子
Input : 127
Output : 127
Input : -67
Output : -67
以下程序将说明byteValueExact()函数的使用:
程序1 :
// Java program to demonstrate byteValueExact() method
import java.io.*;
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating a BigDecimal object
BigDecimal b;
// Creating a byte objects
byte bt;
b = new BigDecimal("47");
// Assigning the byte value of b to bt
bt = b.byteValueExact();
// Displaying the byte value
System.out.println("Exact byte value of " + b + " is " + bt);
}
}
输出。
Exact byte value of 47 is 47
程序2
// Java program to demonstrate byteValueExact() method
import java.io.*;
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// Creating a BigDecimal object
BigDecimal b;
b = new BigDecimal("-128.0564000");
System.out.println("BigDecimal value : " + b);
long roundedValue = Math.round(b.doubleValue());
System.out.println("Rounded value : " + roundedValue);
// Rounding is necessary as the fractional part is not zero
// as well as exceeding the byte range of -128 to 127
b = new BigDecimal(roundedValue);
System.out.println("Byte converted value : " + b.byteValueExact());
}
}
输出。
BigDecimal value : -128.0564000
Rounded value : -128
Byte converted value : -128
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#byteValueExact()