Java.math.BigDecimal.longValueExact() Method



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


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

public long longValueExact()



Return Value

This method returns the long value of the BigDecimal Object.


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


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

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      // create 2 long objecs
      long l1,l2;

      bg1 = new BigDecimal("-429");
      bg2 = new BigDecimal("3.3E+10");

      // assign the long value of bg1 and bg2 to l1,l2 respectively
      l1 = bg1.longValueExact();
      l2 = bg2.longValueExact();

      String str1 = "Exact Long value of " + bg1 + " is " + l1;
      String str2 = "Exact Long value of " + bg2 + " is " + l2;

      // print l1,l2 values
      System.out.println( str1 );
      System.out.println( str2 );

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

Exact Long value of -429 is -429
Exact Long value of 3.3E+10 is 33000000000