Number.isSafeInteger()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Number.isSafeInteger()
は静的メソッドで、指定された値が安全な整数であるかどうかを判定します。
試してみましょう
function warn(x) {
if (Number.isSafeInteger(x)) {
return "Precision safe.";
}
return "Precision may be lost!";
}
console.log(warn(Math.pow(2, 53)));
// Expected output: "Precision may be lost!"
console.log(warn(Math.pow(2, 53) - 1));
// Expected output: "Precision safe."
構文
Number.isSafeInteger(testValue)
引数
testValue
-
安全な整数かどうかをテストする値です。
返値
論理値で、与えられた数値が安全な整数である数値であれば true
を返します。そうでなければ false
です。
解説
安全な整数とは、 -(253 - 1) から 253 - 1 までのすべての整数であり、両端を含みます (±9,007,199,254,740,991)。安全な整数は次のようなものです。
- 正確に IEEE-754 倍精度数として表現することができる
- その IEEE-754 表現は、他の整数を IEEE-754 の表現に適合するように、丸めた結果にはならない
例えば、253 - 1 は安全な整数です。正確に表現することができ、他の整数は、どの IEEE-754 丸めモードの下で丸めたものにもなっていません。対照的に、253 は安全な整数ではありません。これは IEEE-754 で正確に表現できますが、整数値 253 + 1 は直接 IEEE-754 では表現できず、四捨五入や切り捨ての丸めによって 253 になるからです。
完全な精度で ~9 千兆より大きい値や小さい値を扱うには、任意精度演算ライブラリーを使用する必要があります。数値の浮動小数点表現の詳細については、 What Every Programmer Needs to Know about Floating Point Arithmetic を参照してください。s
巨大な整数値については、 BigInt
型を使用することを検討してください。
例
isSafeInteger() の使用
Number.isSafeInteger(3); // true
Number.isSafeInteger(2 ** 53); // false
Number.isSafeInteger(2 ** 53 - 1); // true
Number.isSafeInteger(NaN); // false
Number.isSafeInteger(Infinity); // false
Number.isSafeInteger("3"); // false
Number.isSafeInteger(3.1); // false
Number.isSafeInteger(3.0); // true
仕様書
Specification |
---|
ECMAScript® 2025 Language Specification # sec-number.issafeinteger |
ブラウザーの互換性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
isSafeInteger |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support