Java BigDecimal byteValueExact example

With this example, working of byteValueExact() method in getting exact byte value from a bigdecimal object is demonstrated.

Java BigDecimal byteValueExact example

With this example, working of byteValueExact() method in getting exact byte value from a bigdecimal object is demonstrated.

Java BigDecimal byteValueExact example

Java BigDecimal byteValueExact example

     


With this example, working of byteValueExact() method in getting exact byte value from a bigdecimal object is demonstrated. This method transfigures(changes) a bigdecimal object value into a byte data type value.

Method throws Arithmetic Exception in following two cases. 

Firstly when the fractional part value of bigdecimal object is nonzero. Secondly if any how the value does not fit in byte,  may be due to over flowing case in which the number surpasses (exceeds) the defined byte range ( -128 to 127). 

Syntax for using byteValueExact() method: public byte byteValueExact()
  byte_VariableName = bigdecimal_objectName.byteValueExact();

In bigdecimal to byte transformation, sometimes the bigdecimal values needs rounding, as byte can hold only non-decimal values. This is necessary because as mentioned above, method throws Arithmetic Exception while converting a bigdecimal value that has a non-zero fractional part.

Java_BigDecimal_byteValueExact.java

import java.math.BigDecimal;
import java.math.*;

public class Java_BigDecimal_byteValueExact {
  public static void main(String args[]) {
  double rose = 246.0;
  // byte range -128 to 127

  BigDecimal jack = new BigDecimal(rose);

  // Rounding is necessary as byte can not hold decimal values
  System.out.println("This value does not fit into byte "
  "data type range so its printing will" +
  " generate Arithmetic Exception");
  System.out.println("BigDecimal value : "
  + jack.doubleValue());
  System.out.println("rounded value : "
  + Math.round(jack.doubleValue()));

  /* With the below print statement an 
  ArithmeticException is generated
  because the value does not fit into byte range
  
  System.out.println("byte converted value :" 
  + jack.byteValueExact());
  */

  jack = new BigDecimal("-128.0564000");
  System.out.println("\n\nBigDecimal value : " + jack);

  long roundedValue = Math.round(jack.doubleValue());
  System.out.println("Rounded value : " + roundedValue);

  jack = new BigDecimal(roundedValue);
  System.out.println("Rounding is necessary as the fractional "
  "part of number is not zero");
  System.out.println("byte converted value : " 
  + jack.byteValueExact());

  }
}

Download the source code