javascript 整数であるかを判定する

javascript 整数であるかを判定する

javascriptで、整数であるかを判定するサンプルコードを記述してます。「Number.isInteger」を使用することで判定することができます。「文字列の数値」や「NaN」、「Infinity」は「false」と判定されます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 107.0.5304.63

整数であるかを判定する

整数であるかを判定するには「Number.isInteger」を使用します。

console.log(Number.isInteger(10));   // true

console.log(Number.isInteger(-10));   // true

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

console.log(Number.isInteger(0));    // true

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

console.log(Number.isInteger(-10.1)); // false

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

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

console.log(Number.isInteger(-Infinity)); // false

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

サンプルコード

以下は、
「実行」ボタンをクリックすると、テキストフォームに入力された値が整数であるかを判定して表示する
サンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="utf-8">
    <title>mebeeサンプル</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

    window.onload = () => {

        btn.onclick = () => {
          Number.isInteger(Number(txt.value)) ? foo.innerHTML = "整数です" : foo.innerHTML = "整数ではありません"
        }

    }

</script>

<body>
    <div class="container mx-auto my-56 w-64 px-4">

        <div id="sample" class="flex flex-col justify-center">

            <h1 class="font-semibold text-red-500 text-lg mr-auto">実行結果</h1>

            <p id="foo" class="font-semibold text-lg mr-auto"></p>

            <input
                class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                id="txt" type="text">

            <button id="btn"
                class="mb-2 md:mb-0 bg-transparent hover:bg-red-500 text-red-700 font-semibold hover:text-white py-2 px-4 border border-red-500 hover:border-transparent rounded">
                実行
            </button>

        </div>

    </div>
</body>

</html>

判定されていることが確認できます。