Borislav Hadzhiev
Sun Oct 17 2021·2 min read
Photo by Willian Justen
To check if a string is a positive integer:
Number.isInteger()
method. The method returns true
if the provided value is an integer and
false
otherwise.0
.function isPositiveInteger(str) { if (typeof str !== 'string') { return false; } const num = Number(str); if (Number.isInteger(num) && num > 0) { return true; } return false; } console.log(isPositiveInteger('0')); // 👉️ false console.log(isPositiveInteger('1')); // true console.log(isPositiveInteger('-1')); // 👉️ false console.log(isPositiveInteger('1.5')); // 👉️ false console.log(isPositiveInteger('test')); // false console.log(isPositiveInteger('')); // 👉️ false console.log(isPositiveInteger(' ')); // 👉️ false
We first check if the passed in value isn't a string. In this case we return
false
straight away because the function only handles strings.
We convert the string to a number and store the value into a variable.
Here are some examples of converting a string to a number.
console.log(Number('1')); // 👉️ 1 console.log(Number('1.5')); // 👉️ 1.5 console.log(Number('')); // 👉️ 0 console.log(Number(' ')); // 👉️ 0 console.log(Number('hello')); // 👉️ NaN
In short, if the string contains any non-numeric characters (not 0-9), we get
NaN
(not a number) back.
If it's an empty string or contains spaces, we get 0
back.
The first condition in our if
statement checks if the value is a valid
integer.
The
Number.isInteger
method returns true
if the provided value is an integer and false
otherwise.
Here are some examples of using the Number.isInteger
method directly.
console.log(Number.isInteger(1)); // 👉️ true console.log(Number.isInteger(1.5)); // 👉️ false console.log(Number.isInteger('1')); // 👉️ false console.log(Number.isInteger(-1)); // 👉️ true
We use the
logical AND (&&)
operator to chain another condition. For our if
block to run both conditions
have to be true
.
In our second condition, we check if the number is greater than 0
.
0
, we have a positive integer.However, there is a caveat with the Number.isInteger
method. The method
returns true
if the passed in value:
Here are examples of floats that can be represented as integers:
// 👇️ true console.log(Number.isInteger(10.0)); // 👇️ true console.log(Number.isInteger(10.000000000000000123));
It depends on your use case, however most applications are ok with considering
numbers such as 1.0
and 2.0
to be integers.