The BigDecimal.longValue() method converts a BigDecimal object to a long value by discarding its fractional part. If the numeric value exceeds the range of long, only the lower 64 bits of the result are returned, which may lead to data loss or sign change.
Example:
import java.math.BigDecimal;
class GFG {
public static void main(String[] args) {
BigDecimal bd = new BigDecimal("1234.56");
long value = bd.longValue();
System.out.println(value);
}
}
Output
1234
Explanation: "longValue()" method truncates the decimal portion (.56) and returns only the integer part as a long.
Syntax
public long longValue()
- Parameters: This method does not accept any parameters.
- Return Value: Returns the long value of the given BigDecimal after truncating the decimal part.
BigDecimal.longValue() with Overflow
This example shows how BigDecimal.longValue() behaves when the value exceeds the range of the long data type.
import java.math.BigDecimal;
class GFG {
public static void main(String[] args) {
BigDecimal b1 = new BigDecimal("267694723232435121868");
BigDecimal b2 = new BigDecimal("72111184561789104423");
long v1 = b1.longValue();
long v2 = b2.longValue();
System.out.println("The Long Value of " + b1 + " is " + v1);
System.out.println("The Long Value of " + b2 + " is " + v2);
}
}
Output
The Long Value of 267694723232435121868 is -9006437873208152372 The Long Value of 72111184561789104423 is -1675791733049102041
Explanation:
- If the value is larger than Long.MAX_VALUE or smaller than Long.MIN_VALUE, only the lower 64 bits are returned.
- This can cause data loss and may even result in a value with the opposite sign.