Learn javascript number function to check input is a number, how to check range, eval function 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.
JavaScript has in-built Number() Function
Let's take a look at some example how to convert different object values to numbers using Number() Function in JavaScript
<script> var a1 = new Date(); var a2 = true; var a3 = false; var a4 = 99.99; var a5 = "999"; var a6 = "999 888"; document.write(Number(a1)); document.write(Number(a2)); document.writeln(Number(a3)); document.writeln(Number(a4)); document.writeln(Number(a5)); document.writeln(Number(a6)); </script>
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
<script> var n1 = 10; var n2 = 5; var stringFormat = n1 + " + " + n2; document.writeln(stringFormat); // 10 + 5 // using eval method document.writeln(eval(stringFormat)); // 15 </script>
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
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?"; if(isNaN(inputV1)) console.log("Please enter number"); else console.log("You are "+ inputV1);
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