w3resource

JavaScript: Find out if a number is a natural number or not

JavaScript Math: Exercise-12 with Solution

Check Natural Number

Write a JavaScript function to find out if a number is a natural number or not.

Note:
Natural numbers are whole numbers from 1 upwards : 1, 2, 3, and so on ... or from 0 upwards in some area of mathematics: 0, 1, 2, 3 and so on ...
No negative numbers and no fractions.
Test Data:
console.log(is_Natural(-15));
console.log(is_Natural(1));
console.log(is_Natural(10.22));
console.log(is_Natural(10/0));
Output:
false
true
false
false

Visual Presentation:

JavaScript: Math - Find out if a number is a natural number or not

Sample Solution:

JavaScript Code:

// Define a function named is_Natural that checks if a number is a natural number.
function is_Natural(n) 
{
    // Check if the input is not a number, if so, return 'Not a number'.
    if (typeof n !== 'number') 
        return 'Not a number'; 
    
    // Check if the number is non-negative, an integer, finite, and not Infinity.
    return (n >= 0.0) && (Math.floor(n) === n) && n !== Infinity;
}

// Output the result of checking if -15 is a natural number to the console.
console.log(is_Natural(-15));
// Output the result of checking if 1 is a natural number to the console.
console.log(is_Natural(1));
// Output the result of checking if 10.22 is a natural number to the console.
console.log(is_Natural(10.22));
// Output the result of checking if 10/0 is a natural number to the console.
console.log(is_Natural(10/0));

Output:

false
true
false
false

Flowchart:

Flowchart: JavaScript Math- Find out if a number is a natural  or not

Live Demo:

See the Pen javascript-math-exercise-12 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that checks if a number is a natural number (non-negative integer) without using built-in functions.
  • Write a JavaScript function that validates whether a number is natural and handles both 0-based and 1-based definitions.
  • Write a JavaScript function that returns a boolean indicating if an input is a natural number, rejecting fractional or negative values.
  • Write a JavaScript function that uses bitwise operators to determine if a number is natural by comparing it to its floored value.

Go to:


PREV : LCM of Multiple Numbers.
NEXT : Check Power of 2.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.