Javascript Number ( ) function enables you to convert the value of an object to a number. You can convert string to Number by using Javascript convert Number function but there should not be any string character in string value passed to the number function. If you will pass the string value to the Number function of javascript having any string character then it will return NaN. NaN stands for “Not a Number” in JavaScript.
If Date object is passes to the number function then it returns value in milliseconds. It counts the number of milliseconds since midnight 1 January, 1970 UTC (Universal Coordinated Time).
JavaScript Number Function Syntax
Number(object);
Number function takes 1 argument as object type.
Javascript Convert to Number Function Examples
Example 1
var num1 = new String("12345");
document.write(Number(num1));
Example 2
var num2 = new String("12 34a");
document.write(Number(num2));
In this example output will be NaN i.e. Not a Number coz num2 variable has a string value with string characters along with numeric characters.
Example 3
var num3 = new Date(); document.write(Number(num3));
Number of milliseconds since midnight 1 January, 1970 to the time when the Number function was executed.
Javascript Number function returns 1 or 0 for the Boolean type objects corresponding to true or false value. It returns 0 for false and 1 for true.
E.g.:
var num4 = new Boolean(true); document.write(Number(num4)); var num5 = new Boolean(false); document.write(Number(num5));
Continue to next tutorial: Javascript parseFloat function to learn how to convert string value into numeric float value.