BigDecimal longValue() Method in Java
The java.math.BigDecimal.longValue() is an in-built function which converts this BigDecimal to a long value. This function discards any fractional part of this BigDecimal. The function returns only the lower-order 64 bits when the result of the conversion is too big to be represented as a long value.
Syntax:
public long longValue()
Parameters: This function accepts no parameters.
Return Value: This function returns the long value of this BigDecimal.
Examples:
Input : 1987812456121.176
Output : 1987812456121
Input : "721111"
Output : 721111
Below programs illustrate the use of java.math.BigDecimal.longValue() method:
Program 1:
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
BigDecimal b1, b2;
b1 = new BigDecimal( "1987812456121.176" );
b2 = new BigDecimal( "721111" );
System.out.println( "The Long Value of " + b1 +
" is " + b1.longValue());
System.out.println( "The Long Value of " + b2 +
" is " + b2.longValue());
}
}
|
Output:
The Long Value of 1987812456121.176 is 1987812456121
The Long Value of 721111 is 721111
Note: Information regarding the overall magnitude and precision of large this BigDecimal values might be lost during the course of conversion by this function. As a consequence, a result with the opposite sign might be returned.
Program 2: Below program illustrates a scenario when the function returns a result with the opposite sign.
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
BigDecimal b1, b2;
b1 = new BigDecimal( "267694723232435121868" );
b2 = new BigDecimal( "72111184561789104423" );
System.out.println( "The Long Value of " + b1 +
" is " + b1.longValue());
System.out.println( "The Long Value of " + b2 +
" is " + b2.longValue());
}
}
|
Output:
The Long Value of 267694723232435121868 is -9006437873208152372
The Long Value of 72111184561789104423 is -1675791733049102041
Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#longValue()
Last Updated :
04 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...