Contents
JavaScript Convert String to Number: Main Tips
- This function is used to convert object arguments into numbers, which represent the object value.
- If the specified value cannot be converted into a legal number, NaN is returned.
Method Explained
In JavaScript, it is possible to include numbers as either actual numbers or objects. JavaScript convert string to number function is a built-in method, allowing developers to receive object values in a number format quickly.
This function is considered to be the most beneficial when developers want to receive variable values in legal numbers. JavaScript convert string to number function is used to convert object arguments into numbers, which represent the object value.
In some instances, the specified value cannot be converted into a legal number. Then, NaN
is returned instead.
var var1 = false;
var var2 = true;
var var3 = "123";
var var4 = "123 456";
var num =
Number(var1) + "<br>" +
Number(var2) + "<br>" +
Number(var3) + "<br>" +
Number(var4);
Note: In case the parameter happens to be a date object, this function will return the number of milliseconds that have passed from 1970 UTC, January 1st, midnight, to now.
To implement the JavaScript convert string to number method, you can also use parseInt() function. This method is often used to convert string to Int JavaScript.
Learn Syntax
The syntax of JavaScript number function is not to be feared: you can master it quickly. Remember the correct capitalization, and bear in mind that you should include an object you wish to convert to a number in the parentheses:
Number(object)
JavaScript number function will work even if you don't include the object
argument. While the standard rule for this JavaScript convert string to number function is that you have to specify which object's value you wish to convert to a number, nothing will explode if you don't!
The string to number JavaScript function can take any object as the parameter. If no argument is put into the parentheses, the function will automatically return 0.
Return Value
String to number JavaScript method can have several outcomes. If you indicate a specific object argument, the value of that object will be converted into a legal number. In cases when the function won't be able to generate a legal number, you will notice NaN
which means that the variable is not a number.
If the argument is not included in the JavaScript convert string to number function, the return value will be 0. This information is illustrated in the table below:
Return Value: | Returns object values if they can be translated into legal numbers. Returns NaN if a value cannot be converted into a legal number. Returns 0 if no argument is provided. |
---|---|
JavaScript Version: | ECMAScript 1 |