Java.math.BigDecimal.intValueExact() Method



The java.math.BigDecimal.intValueExact()converts this BigDecimal to an int, checking for lost information. If this BigDecimal has a nonzero fractional part or is out of the possible range for an int result then an ArithmeticException is thrown.


Following is the declaration for java.math.BigDecimal.intValueExact() method.

public int intValueExact()



Return Value

This method returns the int value of the BigDecimal Object.


ArithmeticException − If this has a nonzero fractional part, or will not fit in an int.


The following example shows the usage of math.BigDecimal.intValueExact() method.

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      //Create two int Object
      int i1, i2;

      bg1 = new BigDecimal("40");
      bg2 = new BigDecimal("4E+1");

      // assign the exact int value of bg1 and bg2 to i1,i2 respectively
      i1 = bg1.intValueExact();
      i2 = bg2.intValueExact();

      String str1 = "Exact int value of " + bg1 + " is " + i1;
      String str2 = "Exact int value of " + bg2 + " is " + i2;

      // print i1,i2 values
      System.out.println( str1 );
      System.out.println( str2 );

Let us compile and run the above program, this will produce the following result −

Exact int value of 40 is 40
Exact int value of 4E+1 is 40