Free Web Development Online Tutorials, Learn to Code
Learn JavaScript, Free JavaScript Tutorial for Beginners, Interactive JavaScript Examples

Number and Eval Methods in Javascript

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 to Number

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>
    
After executing the above code here is the result
Use of eval() function 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

<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>
Number to String in JavaScript
            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
                

Comment
Name
Email
Website
Subscribe