javascript 整数が53bit(2の53乗)-1の範囲であるかを判定する

javascript 整数が53bit(2の53乗)-1の範囲であるかを判定する

javascriptで、isSafeIntegerを使って、整数が53bit(2の53乗)-1である「 9007199254740991 」の範囲であるかを判定するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

isSafeInteger使い方

isSafeIntegerを使用すると、利用しようとしている整数が53bit(2の53乗)-1である「 9007199254740991 」の範囲であるかを判定することが可能です。

console.log(
  Number.isSafeInteger( Math.pow( 2, 53 ) - 1 ) // true
);

console.log(
  Number.isSafeInteger( Math.pow( 2, 53 ) ) // false
);

console.log(
  Number.isSafeInteger( -Math.pow( 2, 53 ) ) // false
);

「NaN」や「Infinity」なども「false」になります。

console.log(
  Number.isSafeInteger( NaN ) // false
);

console.log(
  Number.isSafeInteger( Infinity ) // false
);

console.log(
  Number.isSafeInteger( undefined ) // false
);

console.log(
  Number.isSafeInteger( '10' ) // false
);

console.log(
  Number.isSafeInteger( [10] ) // false
);

console.log(
  Number.isSafeInteger( true ) // false
);

console.log(
  Number.isSafeInteger( false ) // false
);

なお、少数は「false」になりますが、「.0」の場合は「true」と判定されます。

console.log(
  Number.isSafeInteger( 10.1 ) // false
);

console.log(
  Number.isSafeInteger( 10.0 ) // true
);

console.log(
  Number.isSafeInteger( 10.000 ) // true
);

BigIntについて

ちなみに、「BigInt」を使用しないと、53bit(2の53乗)である「 9007199254740992 」以上の数値を扱うと以下のように演算の結果がおかしくなります。

console.log(
  Math.pow( 2, 53 ) + 1 // 9007199254740992
);

console.log(
  Math.pow( 2, 53 ) // 9007199254740992
);

// bigint使用
console.log(
  2n ** 53n + 1n // 9007199254740993n
);

実行結果

また、「BigInt」は「isSafeInteger」で判定すると「false」となります。

console.log(
  Number.isSafeInteger( 2n ) // false
)