I don't think isNaN is gonna work for my situation. I want to make sure a certain variable only contains whole numbers when I validate it. So -1.45 in my case should not be allowed. Values such as 1, 23, 334 should be allowed/valid.
PART #1:
You can use remainder operator to find if a value is whole number or not like:
function isWholeNumber(value) {
if (value % 1 === 0) {
console.log(value + ' is a whole number');
} else {
console.log(value + ' is not a whole number');
}
}
// Display the result here
isWholeNumber(1.45);
isWholeNumber(23);
Explanation:
1.45 % 1
returns 0.44999999999999996
and 23 % 1
returns 0
.value % 1 === 0
, then we can say that value
is a whole number else not.PART #2:
This logic fails in some cases where value
is not actually a number
, as remainder operator (%) converts its operands to numbers like:
function isWholeNumber(value) {
console.log(value % 1); //<--- result is always 0
if (value % 1 === 0) {
console.log(value + ' is a whole number');
} else {
console.log(value + ' is not a whole number');
}
}
// Display the result here
isWholeNumber('23');
isWholeNumber('');
isWholeNumber(true);
This result in a display of incorrect results like empty string and boolean value display as the whole number. We can fix this by checking of type of value is number
like:
function isWholeNumber(value) {
if (typeof value === 'number' && value % 1 === 0) {
console.log(value + ' is a whole number');
} else {
console.log(value + ' is not a whole number');
}
}
// Display the result here
isWholeNumber(1.45);
isWholeNumber(24);
isWholeNumber('23');
isWholeNumber('');
isWholeNumber(true);
PART #3:
In ES6 global object Number
got a new property Number.isInteger(value)
. It checks whether value
is a whole number like:
// Display the result here
console.log(Number.isInteger(1.45));
console.log(Number.isInteger(24));
console.log(Number.isInteger('23'));
console.log(Number.isInteger(''));
console.log(Number.isInteger(true));
We can integrate this with our modified isWholeNumber
function in part #2 like:
function isWholeNumber(value) {
if (Number.isInteger(value)) {
console.log(value + ' is a whole number');
} else {
console.log(value + ' is not a whole number');
}
}
// Display the result here
isWholeNumber(1.45);
isWholeNumber(24);
isWholeNumber('23');
isWholeNumber('');
isWholeNumber(true);
isNaN()
is to check number or not .It will not check the number is whole or not.
function isInt(n) {
return n % 1 === 0;
}
or
if (number % 1 == 0) {
alert('Whole Number');
} else {
alert('Not a Whole Number');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With