Java中的 BigDecimal floatValue() 方法及示例
Java.math.BigDecimal .floatValue()将此 BigDecimal 转换为浮点数。如果此 BigDecimal 的量级太大而无法表示为浮点数,则会酌情将其转换为 Float.NEGATIVE_INFINITY 或 Float.POSITIVE_INFINITY。请注意,即使返回值是有限的,这种转换也会丢失有关 BigDecimal 值精度的信息。
句法:
public float floatValue()
参数:此函数不接受任何参数。
返回:该方法返回一个浮点值,表示此 BigDecimal 的浮点值。
例子:
Input: BigDecimal1 = 1234
Output: 1234.0
Input: BigDecimal1 = 21545135451354545
Output: 2.15451365E16
Explanation:
BigInteger1.floatValue() = 2.15451365E16.
This BigDecimal 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.
下面的程序说明了 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: Java/math/BigDecimal.html#floatValue()