What is the BigDecimal.byteValueExact() method in Java?

A BigDecimal is an immutable, arbitrary-precision signed decimal number. BigDecimal contains 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. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Read more about the BigDecimal class here

The byteValueExact method of the BigDecimal class converts the value of the BigDecimal to a byte value.

An ArithmeticException is thrown:

  • If the value contains non-zero fractional parts.
  • If the value is larger than the maximum value the byte can hold.

Syntax

public byte byteValueExact()

Parameters

This method doesn’t take any parameters.

Return value

This method returns the BigDecimal value as a byte value.

Code

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);
}
}
}

Explanation

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.

Free Resources