Join Class

Number validation in javascript example

Learn javascript number function to check input is a number, how to check range, eval function, check number validation in javascript example.

In JavaScript there is only one type for all numbers, all numbers are treated as floating-point numbers. though the dot is not displayed if there is no digit after the decimal point.

Converting object to Number

JavaScript has in-built Number function to convert any object to number, Let's take a look at some examples of how to convert different object values to numbers using Number() function in JavaScript.

    var a1 = new Date();
    var a2 = true;
    var a3 = false;
    var a4 = 99.99;
    var a5 = "999";
    var a6 = "999 888";

After executing the above code here is the result!

use eval function to check number in JavaScript

Now think of a situation where you receive user input as number and do some calculation based on that. Suppose you receive a number as string, but you need to perform some calculation, in such scenario you have to use eval() function.

eval() is used for evaluating the expression for number validation in javascript.

    var n1 = 10;
    var n2 = 5;
    var stringFormat = n1 + " + " + n2;
    document.writeln(stringFormat); // 10 + 5
    // using eval method
    document.writeln(eval(stringFormat)); // 15
Number to String in JavaScript

There is built-in toString() method in javscript to convert a integer value to a string.

            var x = 721;  
x.toString();            // returns 721 from variable x
(123).toString();        // returns 721 from literal 123 
(700 + 21).toString();   // returns 721 from expression 700 + 21
Check input is number in JavaScript

You can check input is number in JavaScript using isNaN function this is a built-in function, simply check if input is a number.

var inputV1="Your Age?";

    console.log("Please enter number");
    console.log("You are "+ inputV1);
Check number range in javascript

If you want to check if any number is within specified range using JavaScript, there is no built-in function to check range, but you can create a function like example below, here we have three parameters to the function, input value, minimum value and maximum limit.

function isInRange(input, min, max) {
return ((input-min)*(input-max) <= 0);
console.log(isInRange(4, 1, 10));     // true
console.log(isInRange(-2, 1, 10));    // false
console.log(isInRange(11, 1, 10));    // false

The above JavaScript function to check number range- is a custom function, you can give any name; also can change the internal logic if you find more efficient way to do it.

JavaScript programming tutorials to learn JavaScript coding step by step, develop website using JavaScript and html.
Advanced JavaScript
JavaScript Number
javascript Interview Questions Answers
JavaScript Examples | JavaScript Online Course