Java BigDecimal intValue()方法

Java BigDecimal intValue()方法

java.math.BigDecimal.intValue() 是一个内置的函数,可以将这个BigDecimal转换为一个整数值。这个函数抛弃了这个BigDecimal的任何小数部分。如果转换的结果太大,无法表示为一个整数值,该函数只返回低阶的32位。

语法

public int intValue()

参数: 此函数不接受任何参数。

返回值 :该函数返回该BigDecimal的整数值。

举例说明

Input : 19878124.176
Output : 19878124

Input : "721111"
Output : 721111

以下程序说明了 java.math.BigDecimal.intValue() 方法。

程序1 :

// Java program to illustrate
// intValue() 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("19878124.176");
        b2 = new BigDecimal("721111");
        // Displaying their respective Integer Values
        System.out.println("The Integer Value of " + b1 + " is " 
                                                + b1.intValue());
        System.out.println("The Integer Value of " + b2 + " is "
                                                + b2.intValue());
    }
}

输出

The Integer Value of 19878124.176 is 19878124
The Integer Value of 721111 is 721111

注意: 在这个函数的转换过程中,关于大的BigDecimal值的整体大小和精度的信息可能会丢失。因此,可能会返回一个符号相反的结果。

程序2: 这个程序说明了当该函数返回一个相反符号的结果的情况。

// Java program to illustrate
// intValue() 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("1987812417600");
        b2 = new BigDecimal("3567128439701");
        // Displaying their respective Integer Values
        System.out.println("The Integer Value of " + b1 + " is " + b1.intValue());
        System.out.println("The Integer Value of " + b2 + " is " + b2.intValue());
    }
}

输出

The Integer Value of 1987812417600 is -757440448
The Integer Value of 3567128439701 is -1989383275

**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#intValue()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程