How to Convert string to number in JavaScript

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.

parseInt method

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

parseFloat method

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

Number method

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

 

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

2 Comment

SA
manoj sonagra
July 24, 2021

nice one

SA
Harsukh Makwana
July 23, 2021

nice article