What is the BigDecimal.byteValueExact() method in Java?
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:
- 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
BigDecimalobjects,val1,val2, andval3, with values10,10.10, and128, respectively. -
We call the
byteValueExactmethod on theval1object. The method returns theBigDecimalvalue as abyte. The value10can be stored inbyteand has no non-zero fraction, so there will be no exception. -
We call the
byteValueExactmethod on theval2object. The value10.10contains a non-zero fractional part, so anArithmeticExceptionis thrown. -
We call the
byteValueExactmethod on theval3object. The value128is too large to be stored in abyte, so anArithmeticExceptionis thrown.