How to Convert String to Number in JavaScript

How to Convert String to Number in JavaScript

JavaScript is a JavaScript-based programming language. Throughout this article, we will teach you how to convert string to number in JavaScript. We will start with simple examples and advance in complexity as we go.

JavaScript is a programming language that is popular in the web browser environment. JavaScript supports two methods for storing numbers. The first method is to store numbers traditionally, as an integer or floating-point number. The second method is to store them as strings. Converting a string to a number in JavaScript can be done by using parseInt() or parseFloat().

A strict comparison between these two would fail due to their different types.

var num1 = 42;
var num2 = '42';
if (num1 === num2) {
} else {
// Will log `false`

In JavaScript, there are three different ways to convert a string into a number. First, the parseInt() method will take a string and return an integer representation of that string. Second, the parseFloat() method will take a string and return a floating-point representation of that string. Finally, the Number() function will convert any primitive value to an object while preserving its type and associating it with the namespace “Number” instead of “undefined”.


JavaScript has a function called parseInt(). This function takes in a string and converts it to an integer. It is also possible to use parseInt() to convert the other types of numbers mentioned earlier, but this tutorial will focus on strings. The parseInt() function can be used within a program to take input from the user or elsewhere and process that input into an integer.

var text = '42px';
var integer = parseInt(text, 10);
// returns 42


The JavaScript function parseFloat() is a universal way to convert a string into a number. The process begins by converting the string to a string using the parseInt() function. This converts any text in the string into numbers, removing what it can while still maintaining values like “2” or “5”.

var text = '3.14someRandomStuff';
var pointNum = parseFloat(text);
// returns 3.14


Learning how to convert a string to a number is useful when working with JavaScript. The Number() function converts strings into numbers and can be used in many different instances. A good example of the function being utilized is where you have a user inputting their height and weight, but they enter it as a string of text instead of an integer.

// Convert strings
Number('123'); // returns 123
Number('12.3'); // returns 12.3
Number('3.14someRandomStuff'); // returns NaN
Number('42px'); // returns NaN