I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.
Share Improve this question edited Jan 28, 2015 at 14:12 user3072143 asked Jan 28, 2015 at 13:52 user3072143user3072143 871 gold badge2 silver badges8 bronze badges 7- It displays data is not an integer no matter what. Even if i put an integer. – user3072143 Commented Jan 28, 2015 at 13:55
- @user3072143 Check the code snippet :) – Hugo Sousa Commented Jan 28, 2015 at 13:56
- The code you've provided works just fine (click on the "run code snippet" button). The problem is somewhere else. – JJJ Commented Jan 28, 2015 at 13:56
- Works fine for me as well, made a fiddle: jsfiddle.net/legolandbridge/cx1a1g23 – collardeau Commented Jan 28, 2015 at 13:56
- this has ben answered before (use ===): stackoverflow.com/questions/14636536/… – BrendanMullins Commented Jan 28, 2015 at 13:57
3 Answers
Reset to default 13prompt will always return a string so in your case:
var integerAge = parseInt(age);
if(!isNaN(integerAge) && age === '' + integerAge)
alert("data is integer")
else
alert("data is not an integer")
In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0
or custom minimum and maximum in the next validation step.
Prompts always return strings, but since JS is loosely typed language, those Strings will get autocasted into Numbers when needed (Integers are called Numbers in JS), which is why your example works fine.
For a better check, you can use !isNaN
.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
alert(!isNaN('10'));
alert(!isNaN('abc'));
alert(!isNaN(10));
For the lunatic downvoters, here's an optimized version of OP's code:
var age = parseInt(prompt("Please enter your age", "Enter age"), 10);
alert(isNaN(age) ? 'Not a number' : age);
You can try this one to check if its an integer:
function isInteger(x) {
return x % 1 === 0;
}