これを行う方法は他にもあると思いますが、Infinity を使用して、String から Float への変換で妥当な入力をチェックすることができます。少なくとも 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.");
}
}
サンプル出力:
文字列表現: -99999999999999999999999999999999999999999999
isNaN の結果: false
その数値は小さすぎます。
文字列表現: 12345
isNaNの結果: false
その数はまさにそうですね。
文字列表現: 99999999999999999999999999999999999999999999
isNaN の結果: false
その数値は大きすぎます。