Java BigDecimal floatValue()方法及示例

Java BigDecimal floatValue()方法及示例

java.math.BigDecimal .floatValue()将这个BigDecimal转换为浮点数。如果这个BigDecimal的量级太大,无法用浮点数来表示,它将被转换为Float.NEGATIVE_INFINITY或Float.POSITIVE_INFINITY,视情况而定。请注意,即使返回值是有限的,这种转换也会丢失关于BigDecimal值的精度信息。

语法

public float floatValue()

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

返回: 该方法返回一个浮动值,代表这个BigDecimal的浮动值。

举例说明

输入: BigDecimal1 = 1234
输出: 1234.0

输入: BigDecimal1 = 21545135451354545
输出: 2.15451365E16
解释:
BigInteger1.floatValue() = 2.15451365E16。
这个BigDecimal太大
太大,无法用浮点数来表示。
那么它将被转换为
Float.NEGATIVE_INFINITY或
Float.POSITIVE_INFINITY,视情况而定。

下面的程序说明了BigDecimal类的floatValue()方法。

例1:

// Java program to demonstrate
// floatValue() method of BigDecimal
  
import java.math.BigDecimal;
  
public class GFG {
    public static void main(String[] args)
    {
        // For user input
        // Use Scanner or BufferedReader
  
        // Object of String created
        // Holds the value
        String input1
            = "545456468445645468464645";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Using floatValue() method
        float f = a.floatValue();
  
        // Display the result
        System.out.println(f);
    }
}

输出。

5.4545646E23

例2:

// Java program to demonstrate
// floatValue() method of BigDecimal
  
import java.math.BigDecimal;
  
public class GFG {
    public static void main(String[] args)
    {
        // For user input
        // Use Scanner or BufferedReader
  
        // Object of String created
        // Holds the value
        String input1
            = "984522";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Using floatValue() method
        float f = a.floatValue();
  
        // Display the result
        System.out.println(f);
    }
}

输出。

984522.0

参考文献: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#floatValue()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程