If you have noticed in Javascript, a number without quatation mark(For example, 10) is number in data type while with quatation mark(For example, '10') is string in data type.
If you look at the below Javascript code, you will get it.
var x = '10';
var y = 10;
console.log(x == y) // true
console.log(x === y) // false
This is because variable x holds string data type and variable y holds number data type. If you print typeof(x)
, you will get its data type as string
. Now look at the below example, so it makes clear how it makes confusion.
var x = '10';
var y = 10;
console.log(x + y); // 10
In this scenario, first of all, we need to convert string data type to number. In Javascript, there are few methods you can convert string to number.
The parseInt method converts a string to an integer. Now look at the above example with parseInt method.
var x = '10';
var y = 10;
console.log(parseInt(x) + y); // 20
This method returns number if starting characters are number and left are string.
var x = '10x5y';
console.log(parseInt(x)); // 10
But if the first character is alphabet, the function returns NaN means Not a Number. Here are few returns:
console.log(parseInt('10x5y')); // 10
console.log(parseInt('a10x5y')); // NaN
console.log(parseInt('10.20')); // 10
The parseFloat method converts a string to decimal number. You can even pass in strings with random text in them. The parseFloat method is same as parseInt method except, it returns decimal number instead of full number.
console.log(parseFloat('10.5x5y')); // 10.5
console.log(parseFloat('a10x5y')); // NaN
console.log(parseFloat('10.20')); // 10.2
The Number() method converts a string data to a number. If it couldn't convert to number, it returns NaN. This method couldn't covert string to number if string contains any alphabet character. So this method is less used compare to above methods.
console.log(Number('10')); // returns 10
console.log(Number('10.5')); // returns 10.5
console.log(Number('10.5x5y')); // NaN
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
phpMyAdmin Automatic Logout Time
phpMyAdmin is open-source web based appl...Laravel 8 - Multi Authentication API with Example
In this tutorial, I would like share wit...Get Current time and date in React
In this tutorial, we will discuss how to...How to Install Let's Encrypt on Ubuntu Server
While many web hosting providers provide...Angular 8|9 File Upload with Progress Bar Tutorial
Today we are going to learn how to uploa...