Anjan Dutta
Convert a string to number in Javascript
Convert a string to number in Javascript
Javascript is not a strongly type casted language. And it is very closely coupled to the browser DOM. So, now and then we end up parsing UI components like headings and paragraphs that contain a mix of strings and numbers.
In this article, I am going to describe how to convert a string to number in Javascript.
Convert a string to number in Javascript
We can use parseInt()
function to convert a string to number in Javascript. The parseInt()
function takes 2 parameters. The first parameter should be a string and the second parameter must be the base. We are talking about decimal point numbers here, so the base will be 10 in our case.
See the below example.
let str = '100 dollars';let num = parseInt(str, 10);console.log(num); // 100
This method can’t convert string to floating-point numbers.
For example, the below code will print the integer part of the number.
let str = '14.5 dollars';let num = parseInt(str, 10);console.log(num); // 14
Convert string to a floating-point integer
We can use parseFloat()
method to convert string to a floating-point number. This method takes only one parameter which should be a string.
let str = '14.50 dollars';let num = parseFloat(str, 10);console.log(num); // 14.5
But I’m not sure if the number is integer or floating-point
In such cases, we can use the Number() function. It takes only one parameter which should be a string. Please see below example for details.
let str = '14.50 dollars';console.log( Number(str )); // 14.5 let str2 = '100dollars';console.log( Number(str2 )); // 100
Important Note:
The above examples will work only with a string that starts with a number. For example '123abc'.
But what if the number is not at the beginning of the string?
Then all of the above-mentioned methods will return a "NaN"
.
let str = 'abc123';parseInt(str); // NaNparseFloat(str); // NaNNumber(str); // NaN
Extract a number from any position of a string
We can use a regex match()
method to extract a number from any position of a string. The match()
method returns an array as a result.
let str = 'abc123';let extract = str.match(/\d+$/);console.log(extract[0]); // "123"
In this case, we have to access the 0th index of the array to get the result.
But, what if the string contains multiple numbers.
For example:
let str = 'a20bc123'; let extract = str.match(/\d+$/); console.log(extract[0]); // "20"
This will return the first match, which is 20 in this case.
Extract multiple numbers from different positions of a string
To extract multiple numbers, we have to make a little change in the regex.
str = 'adasd10dsds105';var matches = str.match(/\d+/g);console.log(matches); // ["10", "105"]
The match function returns a string array, so we might need a further conversion of these results based upon the intended use.