我确信还有其他方法可以做到这一点,但您可以使用 Infinity 检查字符串到浮点数转换中的合理输入。至少在 Java 中,Float.isNaN() 静态方法将为具有无限大小的数字返回 false,表明它们是有效数字,即使您的程序可能希望将它们分类为无效。检查 Float.POSITIVE_INFINITY 和 Float.NEGATIVE_INFINITY 常量可以解决这个问题。例如:
// Some sample values to test our code with
String stringValues[] = {
"-999999999999999999999999999999999999999999999",
"12345",
"999999999999999999999999999999999999999999999"
};
// Loop through each string representation
for (String stringValue : stringValues) {
// Convert the string representation to a Float representation
Float floatValue = Float.parseFloat(stringValue);
System.out.println("String representation: " + stringValue);
System.out.println("Result of isNaN: " + floatValue.isNaN());
// Check the result for positive infinity, negative infinity, and
// "normal" float numbers (within the defined range for Float values).
if (floatValue == Float.POSITIVE_INFINITY) {
System.out.println("That number is too big.");
} else if (floatValue == Float.NEGATIVE_INFINITY) {
System.out.println("That number is too small.");
} else {
System.out.println("That number is jussssst right.");
}
}
样本输出:
字符串表示:-999999999999999999999999999999999999999999999
isNaN的结果:false
这个数字太小了。
字符串表示:12345
isNaN 的结果:false
该数字是正确的。
字符串表示:999999999999999999999999999999999999999999999
isNaN的结果:false
这个数字太大了。