Converting And Checking Numbers In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Converting And Checking Numbers In JavaScript.
Converting And Checking Numbers In JavaScript
In JavaScript, you can convert strings to numbers using the Number()
function. This function returns a numerical representation of its argument. For example:
Code For Number() Function
var x = "123";
var y = Number(x);
console.log(y);
Output
123
In addition, there are a few other ways to convert strings to numbers:
Code For parseInt & parseFloat Function
var x = "123";
var y = parseInt(x);
console.log(y);
var x = "123.45";
var y = parseFloat(x);
console.log(y);
Output
123
123.45
It’s also possible to check if a value is a number using the isNaN()
function. The function returns true
if the argument is not a number, and false
otherwise. For example:
Code For isNaN Function In JS
var x = "abc";
console.log(isNaN(x));
var x = 123;
console.log(isNaN(x));
Output
true
false
You can also use the typeof operator to check the type of a value:
Code For typeof Operator In JS
var x = 123;
console.log(typeof x); // number
var x = "abc";
console.log(typeof x); // string
Output
number
string
It’s important to keep in mind that the typeof operator returns a string, so you need to compare it to the string “number” if you want to check if a value is a number:
More Code On typeof Operator In JS
var x = 123;
if (typeof x === "number") {
console.log("x is a number");
} else {
console.log("x is not a number");
}
Conclusion
If you liked this post Converting And Checking Numbers In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.