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