📜  Java中的 BigInteger floatValue() 方法

📅  最后修改于: 2022-05-13 01:55:37.927000             🧑  作者: Mango

Java中的 BigInteger floatValue() 方法

Java.math.BigInteger.floatValue()将此 BigInteger 转换为浮点值。如果此函数返回的值太大而无法表示为浮点数,则它将酌情转换为 Float.NEGATIVE_INFINITY 或 Float.POSITIVE_INFINITY。这种转换可能会丢失有关 BigInteger 值精度的信息。

句法:

public float floatValue()

返回:该方法返回一个浮点值,表示此 BigInteger 的浮点值。

例子:

Input: BigInteger1=32145
Output: 32145.0
Explanation: BigInteger1.floatValue()=32145.0.

Input: BigInteger1=32145535361361525377
Output: 3.2145535E19
Explanation: BigInteger1.floatValue()=3.2145535E19. This BigInteger is too big 
for a magnitude to represent as a float then it will be converted to 
Float.NEGATIVE_INFINITY or Float.POSITIVE_INFINITY as appropriate.

下面的程序说明了 BigInteger 类的 floatValue() 方法:

示例 1:

// Java program to demonstrate floatValue() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Creating 2 BigInteger objects
        BigInteger b1, b2;
  
        b1 = new BigInteger("32145");
        b2 = new BigInteger("7613721");
  
        // apply floatValue() method
        float floatValueOfb1 = b1.floatValue();
        float floatValueOfb2 = b2.floatValue();
  
        // print floatValue
        System.out.println("floatValue of "
                           + b1 + " : " + floatValueOfb1);
        System.out.println("floatValue of "
                           + b2 + " : " + floatValueOfb2);
    }
}
输出:
floatValue of 32145 : 32145.0
floatValue of 7613721 : 7613721.0

示例 2:当返回浮点数太大而无法表示为浮点数时。

// Java program to demonstrate floatValue() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Creating 2 BigInteger objects
        BigInteger b1, b2;
  
        b1 = new BigInteger("32145535361361525377");
        b2 = new BigInteger("7613721535372632367351");
  
        // apply floatValue() method
        float floatValueOfb1 = b1.floatValue();
        float floatValueOfb2 = b2.floatValue();
  
        // print floatValue
        System.out.println("floatValue of "
                           + b1 + " : " + floatValueOfb1);
        System.out.println("floatValue of "
                           + b2 + " : " + floatValueOfb2);
    }
}
输出:
floatValue of 32145535361361525377 : 3.2145535E19
floatValue of 7613721535372632367351 : 7.6137214E21

参考: https: Java/math/BigInteger.html#floatValue()