A
BigDecimalis an immutable, arbitrary-precision signed decimal number.BigDecimalcontains an arbitrary precision integer unscaled value and a 32-bit integer scale. For example, in the value 10.11, 1011 is the unscaled value, and 2 is the scale. TheBigDecimalclass provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Read more about theBigDecimalclass here
The byteValueExact method of the BigDecimal class converts the value of the BigDecimal to a byte value.
An ArithmeticException is thrown:
public byte byteValueExact()
This method doesn’t take any parameters.
This method returns the BigDecimal value as a byte value.
The code below demonstrates how to use the byteValueExact method.
import java.math.BigDecimal;class ByteValueExact {public static void main( String args[] ) {BigDecimal val1 = new BigDecimal("10");BigDecimal val2 = new BigDecimal("10.10");BigDecimal val3 = new BigDecimal("128");System.out.println("ByteValueExact of " + val1 + " : "+ val1.byteValueExact());try{System.out.println("ByteValueExact of " + val2 + " : "+ val2.byteValueExact());} catch(Exception e) {System.out.println("\nException while converting the " + val2 + " - \n" + e);}try{System.out.println("ByteValueExact of " + val3 + " : "+ val3.byteValueExact());} catch(Exception e) {System.out.println("\nException while converting the " + val3 + " - \n" + e);}}}
In the code above:
We create three BigDecimal objects, val1, val2, and val3, with values 10, 10.10, and 128, respectively.
We call the byteValueExact method on the val1 object. The method returns the BigDecimal value as a byte. The value 10 can be stored in byte and has no non-zero fraction, so there will be no exception.
We call the byteValueExact method on the val2 object. The value 10.10 contains a non-zero fractional part, so an ArithmeticException is thrown.
We call the byteValueExact method on the val3 object. The value 128 is too large to be stored in a byte, so an ArithmeticException is thrown.