Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is BigDecimal.intValueExact() method in Java?

Programming Bytes

BigDecimal is an immutable arbitrary-precision signed decimal number. It contains 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. The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. Read more about BigDecimal class here.

The intValueExact method of the BigDecimal class converts the value of the BigDecimal to an int value.

An ArithmeticException is thrown:

  • If the value contains non-zero fractional parts.
  • If the value is larger than the maximum value an int type can hold.

Syntax

public int intValueExact()

This method doesn’t take any arguments.

This method returns the BigDecimal value as an int value.

Code

The code below demonstrates how to use the intValueExact method:

import java.math.BigDecimal;

class IntValueExact {
    public static void main( String args[] ) {
        BigDecimal val1 = new BigDecimal("10");
        BigDecimal val2 = new BigDecimal("10.10");
        BigDecimal val3 = new BigDecimal("2147483647");
        System.out.println("IntValueExact of " + val1 + "  : "+ val1.intValueExact());
        try{
          System.out.println("IntValueExact of " + val2 + "  : "+ val2.intValueExact());
        } catch(Exception e) {
          System.out.println("\nException while converting the " + val2 + " - \n" + e);
        }
        
        try{
          System.out.println("IntValueExact of " + val3 + "  : "+ val3.intValueExact());
        } catch(Exception e) {
          System.out.println("\nException while converting the " + val3 + " - \n" + e);
        }
    }
}
Examples of "intValueExact()" method

Explanation

In the code above,

  • We create three BigDecimal objects val1, val2, and val3 with values 10, 10.10, and 2147483647 , respectively.

  • We call the intValueExact method of the val1 object. This will return the BigDecimal value as int. The value 10 can be stored in int and has no non-zero fractions, so there will be no exception.

  • We call the intValueExact method of the val2 object. The value 10.10 contains a non-zero fractional part, so an ArithmeticException is thrown.

  • We call the intValueExact method of the val3 object. The value 2147483647 is too large to be stored in int, so an ArithmeticException is thrown.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring