Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is BigDecimal.longValueExact() 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 at about BigDecimal class here.

The longValueExact method of the BigDecimal class converts the value of the BigDecimal to a long value.

An ArithmeticException is thrown:

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

Syntax

public long longValueExact()

This method doesn’t take any arguments.

This method returns the BigDecimal value as a long value.

Code

The code below demonstrates how to use the longValueExact method:

import java.math.BigDecimal;

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

Explanation

In the code above,

  • We create three BigDecimal object val1, val2, and val3 with value 10, 10.10, and 9223372036854775808 respectively.

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

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

  • We call the longValueExact method of the val3 object. The value 9223372036854775808 is too large to be stored in long so an ArithmeticException is thrown.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring