Java BigDecimal longValue()方法
java.math.BigDecimal.longValue() 是一个内置的函数,可以将这个BigDecimal转换为一个长值。这个函数会舍弃这个BigDecimal的任何小数部分。当转换的结果太大,无法表示为长值时,该函数只返回低阶的64位。
语法
public long longValue()
参数: 此函数不接受任何参数。
返回值: 此函数返回此BigDecimal的长值。
举例说明
Input : 1987812456121.176
Output : 1987812456121
Input : "721111"
Output : 721111
以下程序说明了java.math.BigDecimal.longValue()方法的使用。
程序1 :
// Java program to illustrate
// longValue() method
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Creating 2 BigDecimal Objects
BigDecimal b1, b2;
// Assigning values to b1, b2
b1 = new BigDecimal("1987812456121.176");
b2 = new BigDecimal("721111");
// Displaying their respective Long Values
System.out.println("The Long Value of " + b1 +
" is " + b1.longValue());
System.out.println("The Long Value of " + b2 +
" is " + b2.longValue());
}
}
输出。
The Long Value of 1987812456121.176 is 1987812456121
The Long Value of 721111 is 721111
注意: 在这个函数的转换过程中,关于大的BigDecimal值的整体大小和精度的信息可能会丢失。因此,可能会返回一个符号相反的结果。
程序2: 下面的程序说明了当函数返回一个相反符号的结果时的情况。
// Java program to illustrate
// longValue() method
import java.math.*;
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Creating 2 BigDecimal Objects
BigDecimal b1, b2;
// Assigning values to b1, b2
b1 = new BigDecimal("267694723232435121868");
b2 = new BigDecimal("72111184561789104423");
// Displaying their respective Long Values
System.out.println("The Long Value of " + b1 +
" is " + b1.longValue());
System.out.println("The Long Value of " + b2 +
" is " + b2.longValue());
}
}
输出。
The Long Value of 267694723232435121868 is -9006437873208152372
The Long Value of 72111184561789104423 is -1675791733049102041
**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#longValue()