Java BigDecimal intValueExact() Method with Example

BigDecimal Class intValueExact() method: Here, we are going to learn about the intValueExact() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 05, 2020

BigDecimal Class intValueExact() method

  • intValueExact() method is available in java.math package.
  • intValueExact() method is used to convert this BigDecimal into an exact integer value.
  • intValueExact() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • intValueExact() method may throw an exception at the time of converting BigDecimal to an int.
    ArithmeticException: This exception may throw when this BigDecimal holds fractional part that is other than 0 or the resulting value is not enough to adjust in an int.

Syntax:

    public int intValueExact();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is int, it returns the exact integer representation of this BigDecimal.

Example:

// Java program to demonstrate the example 
// of int intValueExact() method of BigDecimal

import java.math.*;

public class IntValueExactOfBD {
    public static void main(String args[]) {
        // Instantiates two variables val 
        // and str
        long val = 124589425l;
        String str = "100";

        // Initialize two BigDecimal objects  
        BigDecimal b_dec1 = new BigDecimal(val);
        BigDecimal b_dec2 = new BigDecimal(str);

        // to convert this BigDecimal b_dec1
        // into a int, and store in a variable named i_conv
        int i_conv = b_dec1.intValueExact();
        System.out.println("b_dec1.intValueExact(): " + i_conv);
        
        // to convert this BigDecimal b_dec2
        // into a int, and store in a variable named i_conv
        i_conv = b_dec2.intValueExact();
        System.out.println("b_dec2.intValueExact(): " + i_conv);
    }
}

Output

b_dec1.intValueExact(): 124589425
b_dec2.intValueExact(): 100


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.