简体   繁体   中英

How to validate a number being an integer

Recently I have been working on a "spinner" that increases and decreases a number by 1 each time, however I've wanted to add validation to the program so that integers only are accepted (no decimals) however I've been unsuccessful in doing this.

I've researched the use of NaN and parseValue(s) but I've not found a way of including this to my script, and any help would be highly appreciated. All code in the example given works as I want it to, therefore I only need the validation.

CODE: HTML

<!DOCTYPE html>
<html>
    <head>
        <h1>Spinners in JavaScript</h1>
    </head>
    <body>
        <p id="textDisplay()">0</p>

        <div align="middle">
            <button onclick="spinUp()">+1</button>
            <button onclick="spinDown()">-1</button>
        </div>
    </body>
</html>

JavaScript

currentNumber = 0;

function spinUp() {
    if(currentNumber==100){
    currentNumber = 0;
    document.getElementById("textDisplay").innerHTML = currentNumber;

    } else if(currentNumber < 100) {
    currentNumber++
    document.getElementById("textDisplay").innerHTML = currentNumber;
    }
}

function spinDown() {
    if(currentNumber>0){
    currentNumber--;
    document.getElementById("textDisplay").innerHTML = currentNumber;

    } else if(currentNumber<=0){
    window.alert("Too low! Higher!");
    currentNumber++;
    document.getElementById("textDisplay").innerHTML = currentNumber;
    }

}

You could use a method like this:

if (number != Math.round(number)){
    alert("Enter a whole number");
  }

You can use the === operator as below :

if (data === parseInt(data, 10))
    alert("data is integer")
else
    alert("data is not an integer")

How to check if a variable is an integer in JavaScript?

v === v | 0;
如果 v 是整数,则为真,否则为假。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM