JavaScript: Converting Strings to Numbers

javascript convert string to numberJavaScript generally does a first-rate job of converting strings to numbers. And that’s a good thing, because as anyone who’s done even a little programming knows, you can’t always assume that something that looks like a number really is a number. The odds are pretty high that it’s really a string.

(And if you’re just starting out with JavaScript, there are plenty of great beginner online  Javascript courses.)

Number, Please!

You can’t always control where the data that you’re working with comes from, or what format it was originally in. You may be getting input from another application or from stored data (perhaps a legacy database), and that input may all be in string format — including data that you need to convert to actual numbers.

So what do you do?

The Basics

The simplest way to convert a string to a number is with the Number() global function. Let’s take a look at how it works:

var string_of_digits = "11.76";
var string_plus_point_five = string_of_digits + .5;
var its_a_number = Number(string_of_digits);
var its_a_number_plus_point_five = its_a_number + .5;
document.write("Here's the string: " + string_of_digits + "<br>");
document.write("Let's add .5 to it: " + string_plus_point_five + "<br>");
document.write("Convert the sting to a number: " + its_a_number + "<br>");
document.write("Add .5 to it: " + its_a_number_plus_point_five + "<br>");

And here’s the output:

Here's the string: 11.76
Let's add .5 to it: 11.760.5
Convert the sting to a number: 11.76
Add .5 to it: 12.26

Is it a Genuine Number?

Now let’s step through it:

First, we set string_of_digits to equal a string: “11.76”. Then we test to see if it really is a string by adding .5 to it — and the result, “11.76.5”, shows that it is a string, since JavaScript simply appended “.5” to it, as if they were both strings.

Next, we use the Number() function to convert it to a number, and set its_a_number to its numeric value. Then we test its_a_number to make sure that it’s a real number by adding .5 to it — and the result, 12.26, shows that it is a real number.

Are We Not Numbers?

The Number() function will work with any object which has a value that can be converted into a number which JavaScript recognizes as legal, including non-string objects such as Date(). But if it doesn’t recognize the value as a number, it will return NaN (“Not a Number”):

var is_it_a_number = Number("11.76.1");
document.write("Is it a number? " + is_it_a_number + "<br>");

And the verdict is:

Is it a number? NaN

Integers to Hexadecimal

It will, however, work with the 0x prefix, indicating that the string represents a hexadecimal number — but only of the string that follows is an integer:

var is_it_a_number = Number("0x125");
document.write("Is it a number? " + is_it_a_number + "<br>");

does work, giving the decimal equivalent of hexadecimal 125 as output:

Is it a number? 293

But see what happens if we try the same thing with a non-integer string:

var is_it_a_number = Number("0x125.1");
document.write("Is it a number? " + is_it_a_number + "<br>");

Suddenly, it’s Not a Number:

Is it a number? NaN

Parse the Number, Please

The Number() function is very useful, but it obviously has some limits. JavaScript, however, does include two other string-to-number functions which are considerably more versatile:  parseInt() and parseFloat(). First, let’s take a look at parseInt():

var is_it_a_number = parseInt("0x125.1");
document.write("Is it a number? " + is_it_a_number + "<br>");

All we did was substitute parseInt() for Number(), but see what happens:

Is it a number? 293

Take the Integer

parseInt() only looked at the integer part of 125.1, and converted it from hexadecimal to decimal; it simply ignored what it didn’t understand.

If the first character in a string is a number, parseInt() will return an integer based on all of the digits it sees until it encounters a non-integer character:

var is_it_a_number = parseInt("99 Luftballons was a hit in 1983");
document.write("Is it a number? " + is_it_a_number + "<br>");

parseInt() returns the first set of integers:

Is it a number? 99

But look what happens with no leading integers:

var is_it_a_number = parseInt("Nena's 99 Luftballons was a hit in 1983");
document.write("Is it a number? " + is_it_a_number + "<br>");

gives us this:

Is it a number? NaN

Leading Blanks

parseInt() will accept leading blank spaces, so this will work:

var is_it_a_number = parseInt("       12");

It will, however, stop when it encounters a trailing blank, as shown in the following example:

var is_it_a_number = parseInt("       12 24");

Both of these examples produce the same output

Is it a number? 12

Base Conversions With parseInt()

And as the first parseInt() example showed, it will accept a leading 0x, indicating a hexadecimal number. But there’s another (and more versatile) way to tell parseInt() what number base to use.  Look at these examples:

var dec_num = parseInt("101");
var hex_num = parseInt("101",16);
var oct_num = parseInt("101",8);
var bin_num = parseInt("101",2);
var whatever_num = parseInt("101",35);
document.write("Decimal: " + dec_num + "<br>");
document.write("Hexadecimal: " + hex_num + "<br>");
document.write("Octal: " + oct_num + "<br>");
document.write("Binary: " + bin_num + "<br>");
document.write("Base 35: " + whatever_num + "<br>");

The number after the comma tells parseInt() what base (or radix) to use; the default (no base) is decimal, and the upper limit is base 36.

Decimal: 101
Hexadecimal: 257
Octal: 65
Binary: 5
Base 35: 1226

Floating Right Along…

The floating-point equivalent of parseInt() is parseFloat(). As the name indicates, it parses a string into a floating-point number. In many respects, it operates like parseInt(). For example, it will accept leading spaces, but it requires the first non-space character it encounters to be a number, and it stops when it reaches a character that it doesn’t understand, including a trailing space.

parseFloat(), however, will recognize a decimal, and continue to parse the number past the decimal:

var is_it_a_number = parseFloat("127.561");
document.write("Is it a number? " + is_it_a_number + "<br>");
Is it a number? 127.561

parseFloat() Is Decimal-Only

parseFloat() will not accept a radix, however, so the following code:

var is_it_a_number = parseFloat("127.561",16);
document.write("Is it a number? " + is_it_a_number + "<br>");

still produces the same output:

Is it a number? 127.561

In the Middle of a String

“OK,” you say, “but what if the number I want is somewhere in the middle of a string?”

That’s an important point, because very often, the number that you want will not be conveniently placed at the beginning of a string. It may be at some very inconvenient location within the string, and you may need to extract it from the string before you can convert it.

There are several ways to do this, depending on the nature of the string, and what you know about the number ahead of time.

Slice it Out

If you know the location of the number within the string, extracting it is a fairly simple task. The easiest way is to use the slice() method to cut away everything in front of the number:

var num_in_middle = "Length: 275.36 inches.";
var is_it_a_number = parseFloat(num_in_middle.slice(8)); 
document.write("Is it a number? " + is_it_a_number + "<br>");
Is it a number? 275.36

As the name implies, slice() returns a slice of the string; the argument (8) tells Slice() where to start — 8 characters into the string. In this case, since we didn’t care about trailing characters, slice() cuts away everything before the number and leaves the trailing characters. If we wanted to, however, we could tell it where to end:

var num_in_middle = "Length: 275.36 inches.";
var is_it_a_number = parseFloat(num_in_middle.slice(8,10)); 
document.write("Is it a number? " + is_it_a_number + "<br>");

Now the slice stops at the tenth character:

Is it a number? 27

You can also use the substr() and substring() methods to extract numbers from known locations within a string; both methods operate in a manner very similar to slice().

Using Regular Expressions

But what if you don’t know the location of the number? That’s an even more common situation; you need to pull a number out of a string, but you don’t know where it is.

That is where regular expressions come in. Regular expressions are a long and complicated subject; there have been more than a few books written about them, and you’re more likely to encounter them in an advanced JavaScript course than in a beginning course.

But for now, here’s what you need to know: Regular expressions form a system for making very precise searches of strings; they are used in a wide variety of programming languages and programming-related environments. The JavaScript search(), replace(), and match() methods use regular expressions to search for, replace, or return specific elements of strings.

Match the Numbers

The following example uses the match() method to extract numbers from a string, based on a regular expression:

var long_winded_string = "Nena's 99 Luftballons was a hit in 1983";
var match_from_string = long_winded_string.match(/\d+/g);
var is_it_a_number = parseInt(match_from_string); 
document.write("Raw match from string: " + match_from_string + "<br>");
document.write("Extract the first number: " + is_it_a_number + "<br>");

The “/\d+/g” argument in match() is a regular expression, telling it to find all (g = global search) substrings of digits (\d+ = any string with at least one digit). It separates the substrings with a comma; we then use parseInt() to extract the first number:

Raw match from string: 99,1983
Extract the first number: 99

You can do much, much more than that with regular expressions, but this example should give you a taste of what is possible with advanced JavaScript programming.