Java BigInteger floatValue()方法
java.math.BigInteger.floatValue() 将这个BigInteger转换为一个浮点数。如果该函数返回的值过大,无法以浮点数表示,那么它将被转换为Float.NEGATIVE_INFINITY或Float.POSITIVE_INFINITY,视情况而定。这种转换有可能会丢失关于BigInteger值的精度信息。
语法
public float floatValue()
返回: 该方法返回一个浮动值,代表这个BigInteger的浮动值。
例子
输入: BigInteger1=32145
输出: 32145.0
解释: BigInteger1.floatValue()=32145.0.
输入: BigInteger1=32145535361361525377
输出: 3.2145535E19
解释: BigInteger1.floatValue()=3.2145535E19. 这个BigInteger太大
太大,无法以浮点数表示,那么它将被转换为
Float.NEGATIVE_INFINITY或Float.POSITIVE_INFINITY,视情况而定。
以下程序说明了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://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#floatValue()