w3resource

JavaScript: Check whether a variable is numeric or not

JavaScript Math: Exercise-16 with Solution

Check If Value is Numeric

Write a JavaScript function to check whether a variable is numerical or not.

Test Data:
console.log(is_Numeric(12));
console.log(is_Numeric('abcd'));
console.log(is_Numeric('12'));
console.log(is_Numeric(' '));
console.log(is_Numeric(1.20));
console.log(is_Numeric(-200));
Output:
true
false
true
false
true
true

Visual Presentation:

JavaScript: Math - Check whether a variable is numeric or not.

Sample Solution:

JavaScript Code:

// Define a function named is_Numeric that checks if a value is numeric.
function is_Numeric(num) {
    // Check if the value can be parsed as a floating-point number and is finite.
    return !isNaN(parseFloat(num)) && isFinite(num);
}

// Output the result of checking if 12 is numeric to the console.
console.log(is_Numeric(12));
// Output the result of checking if 'abcd' is numeric to the console.
console.log(is_Numeric('abcd'));
// Output the result of checking if '12' is numeric to the console.
console.log(is_Numeric('12'));
// Output the result of checking if ' ' (empty string) is numeric to the console.
console.log(is_Numeric(' '));
// Output the result of checking if 1.20 is numeric to the console.
console.log(is_Numeric(1.20));
// Output the result of checking if -200 is numeric to the console.
console.log(is_Numeric(-200));

Output:

true
false
true
false
true
true

Flowchart:

Flowchart: JavaScript Math- Check whether a variable is numeric or not

Live Demo:

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


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to check whether a value is an integer or not.
Next: Write a JavaScript function to calculate the sum of values in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-16.php