The Ultimate Guide to Converting Strings to Numbers in JavaScript

Are you struggling with converting a string to a number in JavaScript? It's a common task whether you are creating front-end user experiences or Nodejs applications, but it can be tricky, especially when the string is not a valid number. Fortunately, there are several methods available to convert a string to a number in JavaScript. In this guide, we'll explore these methods and provide you with a solution to handle non-convertible strings.

JavaScript Convert Strings to Numbers

Using the Number() Function

The Number() method is the most straightforward way to convert a string to a number in JavaScript. It takes a string as an argument and returns a number.


const str = "42";
const num = Number(str);
console.log(num); // Output: 42

One thing to keep in mind is that the Number() function returns NaN (Not a Number) if the string cannot be converted to a number.


const str = "hello";
const num = Number(str);
console.log(num); // Output: NaN

Using the parseInt() Function

Another way to convert a string to a number is by using the parseInt() function. This function takes a string as its argument and returns an integer. If the string starts with a non-numeric character, parseInt() will return NaN.


const str = "42";
const num = parseInt(str);
console.log(num); // Output: 42

const str = "hello";
const num = parseInt(str);
console.log(num); // Output: NaN

By default, parseInt() assumes that the string is in base 10. However, you can specify a different base by passing a second argument to the function.


const str = "1010";
const num = parseInt(str, 2);
console.log(num); // Output: 10 (binary)

Using the parseFloat() Function

If you need to convert a string to a floating-point number, you can use the parseFloat() function. The parseFloat() method is similar to the parseInt() method, but it returns a floating-point number instead of an integer. This function takes a string as its argument and returns a floating-point number. If the string cannot be converted to a number, parseFloat() will return NaN.


const str = "3.14";
const num = parseFloat(str);
console.log(num); // Output: 3.14

When the string is not a valid number, the parseFloat() method returns NaN:


const str = "hello";
const num = parseFloat(str);
console.log(num); // Output: NaN

Using the Math.floor() and Math.ceil() Methods

The Math.floor() and Math.ceil() methods are used to round down and round up a number, respectively. When used to convert a string to a number, they only return a valid number if the string contains an integer. You can use the Math.floor() and Math.ceil() function in combination with parseInt() or parseFloat().


const str = "3.14";
let num = Math.floor(parseFloat(str));
console.log(num); // Output: 3

num = Math.ceil(parseFloat("3.14"));
console.log(num); // Output: 4

When the string is not a valid number, Math.floor() and Math.ceil() return NaN:


let str = "abc";
let num = Math.floor(str);
console.log(num); // Output: NaN

let num2 = Math.ceil(str);
console.log(num2); // Output: NaN

Using the Unary Plus(+) Operator

A less common way to convert a string to a number is by using the unary plus operator. This operator converts its operand to a number and returns it. A + is placed in front of the string, and the resulting value is a positive number.


const str = "42";
const num = +str;
console.log(num); // Output: 42

The unary plus operator can be used in the same way as the Number() method to convert other string representations of numbers, like HEX.


let str2 = "0xFF";
let num2 = +str2;
console.log(typeof num2, num2); // output: number 255

A good application with this trick is to convert color codes from HEX to RGB.

This method is particularly useful if you only need to convert a single string to a number. However, it's important to note that using the unary plus operator can lead to unexpected results if the string contains non-numeric characters.

When the string is not a valid number, the Unary Plus operator returns NaN:


const str = "hello";
const num = +str;
console.log(num); // Output: NaN

One downside of using the unary plus operator is that it can be confusing and hard to read.

Using the Bitwise NOT Operator (~)

The Bitwise NOT operator is another way to convert a string to a number. It is a bitwise operator that performs a bitwise NOT operation on a number, which effectively changes the sign of the number and subtracts one.


let str = "42";
let num = ~-str;
console.log(typeof num, num); // output: number 42

The - operator is used to convert the string to a negative number, and then the Bitwise NOT operator is used to change the sign of the number and subtract one, effectively converting it to a positive number.

Converting Strings to Numbers Using Type Coercion

Type coercion is a process where JavaScript automatically converts a data type into another data type. When you try to perform arithmetic operations on a string in JavaScript, it will attempt to convert the string to a number using type coercion. Here's an example:


let str = "42";
let num = str / 2;
console.log(num); // Output: 21

Note that type coercion can sometimes lead to unexpected results. For example:


let str = "hello";
let num = str / 2;
console.log(num); // Output: NaN (Not a Number)

In this example, since the string "hello" cannot be converted to a number, the result of the arithmetic operation is NaN.

It's generally recommended to avoid type coercion when possible and use explicit type conversion methods like parseInt and parseFloat instead. However, understanding how type coercion works in JavaScript is still important.

Using Regular Expressions

If you need to remove non-numeric characters from a string before converting it to a number, you can use regular expressions.


const str = "42 is the answer!";
const num = parseInt(str.replace(/\D/g, ""));
console.log(num); // Output: 42

This code replaces all non-numeric characters in the string with an empty string, leaving only the numbers.

Converting Hexadecimal and Binary Strings to Numbers

Earlier I mentioned how you could convert a HEX code to a number with the unary plus operator. Let's circle back to that topic with the parseInt method.

In JavaScript, you can use the parseInt() function to convert a hexadecimal or binary string to a number. The parseInt() function takes two arguments: the string to convert and the base of the number system. To convert a hexadecimal string to a number, pass 16 as the second argument to parseInt(). To convert a binary string to a number, you pass 2 as the second argument.

Here's an example:


const hexString = '3A';
const binaryString = '101101';

const hexNumber = parseInt(hexString, 16);
const binaryNumber = parseInt(binaryString, 2);

console.log(hexNumber); // 58
console.log(binaryNumber); // 45

In this example, we convert the hexadecimal string '3A' to a number by passing 16 as the second argument to parseInt(). The resulting number is 58. Similarly, we convert the binary string '101101' to a number by passing 2 as the second argument to parseInt(). The resulting number is 45.

Note that parseInt() can also convert strings in other number systems, such as octal (base 8) and duodecimal (base 12). To convert a string in a different number system, you simply pass the appropriate base as the second argument to parseInt().

Handling errors

It's important to handle cases where a string cannot be converted to a number. In such cases, the methods discussed above will return NaN. You can use the isNaN() function to check for NaN values.


const str = 'not a number';
const num = parseInt(str, 10);

if (isNaN(num)) {
  console.log('Invalid number');
} else {
  console.log(num);
}

Conclusion

There are multiple ways to convert a string to a number in JavaScript. The most commonly used methods are parseInt() and parseFloat(), but the unary plus, ~ operators, Number() constructor, and Regular Expressions can also be used. When using parseInt(), be sure to specify the radix parameter to avoid unexpected results. It's important to handle cases where a string cannot be converted to a number, and you can use the isNaN() function to check for NaN values. With these methods, you can easily convert strings to numbers in JavaScript.

If you enjoyed this article, please consider liking and sharing it with your colleagues and peers. You can also follow me as an author here on C# Corner for more great articles on web development, PWAs, and artificial intelligence.

Thank you again for your support, and I look forward to bringing you more valuable content in the future.


Love2Dev
We specialize in Progressive Web Apps and Web Performance Optimization