Converting string values into numbers is a common task in programming. Often data is passed into applications as strings, even if they represent numeric values. Before you can perform mathematical operations on numeric data, you need to convert the string representation into an actual number.
There are a few ways to convert a string to a number in JavaScript. The most straightforward approach is to use the unary + operator or the Number() function. However, there are some nuances to be aware of when converting strings to numbers, such as handling invalid user input and understanding the difference between decimal, integer, and floating-point numbers.
In this article, we will explore different methods for converting strings to numbers in JavaScript. We will cover:
- Using the unary + operator
- Using the Number() function
- Using parseInt() and parseFloat()
- Converting strings with leading and trailing whitespace
- Handling invalid user input
- Converting numeric strings to integers vs floats
- Performing math operations on converted values
Understanding how to convert between strings and numbers is an essential JavaScript skill. Let’s dive in!
Using the Unary + Operator
The unary + operator can be used to convert a string to a number in JavaScript. Here is an example:
const str = "123"; const num = +str; console.log(typeof num); // number console.log(num); // 123
When the + operator is applied to a string, it converts the string to a number value.
This provides a quick and easy way to convert a numeric string to a number. However, if the string does not contain a valid number, the result will be NaN (Not a Number):
const str = "hello"; const num = +str; console.log(num); // NaN
The + operator can also be used to convert numeric strings containing decimals:
const str = "12.345"; const num = +str; console.log(num); // 12.345
One thing to note is that the + operator always converts to a number without trying to determine if it is an integer or float.
Using the Number() Function
The Number() function can also be used to convert a string to a number:
const str = "456"; const num = Number(str); console.log(typeof num); // number console.log(num); // 456
Just like the + operator, Number() will convert the string to NaN if it does not contain a valid number:
const str = "hello"; const num = Number(str); console.log(num); // NaN
The Number() function handles decimal numbers as well:
const str = "23.456"; const num = Number(str); console.log(num); // 23.456
And Number() will also convert a numeric string to a number without trying to determine if it is an integer or float.
The + operator and Number() function work very similarly for string to number conversion. The main difference is that Number() will actually trim any whitespace from the start and end of the string first:
const str = " 456 "; const num1 = +str; const num2 = Number(str); console.log(num1); // 456 console.log(num2); // 456
So Number() is a bit more robust when dealing with string input that may have extra whitespace.
Using parseInt() and parseFloat()
The parseInt() and parseFloat() functions can convert string values to integers and floats more precisely.
parseInt() will convert a string to an integer number, dropping any fractions:
const str = "123.456"; const num = parseInt(str); console.log(num); // 123
parseFloat() on the other hand will convert a string to a floating point number:
const str = "123.456"; const num = parseFloat(str); console.log(num); // 123.456
These functions are useful when you want to specifically convert a string to a particular numeric type.
parseInt() and parseFloat() will ignore any leading whitespace, but not trailing whitespace:
const str = " 456.789 "; const int = parseInt(str); const float = parseFloat(str); console.log(int); // 456 console.log(float); // 456.789
One key difference between these parsing functions and the + operator/Number() is that parseInt() and parseFloat() will stop parsing when they reach a character that is not a valid number.
For example:
const str = "123abc"; const num1 = +str; // NaN const num2 = Number(str); // NaN const int = parseInt(str); // 123 const float = parseFloat(str); // 123
This allows you to convert strings representing invalid numbers to valid numbers if the invalid characters are at the end of the string.
Converting Strings with Leading and Trailing Whitespace
When converting user input to numbers, there is often the need to trim leading and trailing whitespace from the string first:
const str = " 56 "; const num = +str; // 56
The + operator and parseInt()/parseFloat() will ignore leading whitespace, but not trailing whitespace.
To handle whitespace at the beginning and end of the string, you can chain the string trim() method before converting to a number:
const str = " 67 "; const num = +str.trim(); // 67
Or with Number():
const str = " 89 "; const num = Number(str.trim()); // 89
The trim() method will remove any extra whitespace from the start and end, allowing you to safely convert to a number.
Handling Invalid User Input
When converting user input to numbers, you also need to consider what to do for invalid non-numeric values.
For example, if the user enters a completely invalid string:
const str = "hello"; const num = +str; // NaN
This will return NaN when converted to a number.
Often you want to handle this by either:
- Replacing the NaN with a default number:
const num = +str || 0; // 0
const num = +str; if (isNaN(num)) { throw new Error("Invalid number entered"); }
You can also first check if the string is a valid number before converting:
const str = "123"; if (isNaN(+str)) { // handle error } else { const num = +str; // use valid number }
The key is to anticipate and properly handle scenarios where the user may not enter a valid number.
Converting to Integer vs. Float
When converting a numeric string to a number, you also need to decide whether you want the result to be an integer or float.
As we saw earlier, the + operator and Number() will convert to a number, but won’t distinguish between integers and floats:
const intString = "456"; const floatString = "456.789"; const intNum1 = +intString; // 456 const floatNum1 = +floatString; // 456.789 const intNum2 = Number(intString); // 456 const floatNum2 = Number(floatString); // 456.789
If you specifically want an integer, you can use parseInt():
const intNum = parseInt(intString); // 456 const floatNum = parseInt(floatString); // 456
Or parseFloat() for a float:
const intNum = parseFloat(intString); // 456 const floatNum = parseFloat(floatString); // 456.789
In many cases, the extra precision doesn’t matter. But if you need to distinguish between integer and floating point values, use the appropriate parsing function.
Performing Math Operations on Converted Values
One of the main reasons to convert a string to a number is to then perform math operations on it.
For example:
const intString1 = "5"; const intString2 = "10"; const num1 = +intString1; // 5 const num2 = +intString2; // 10 const sum = num1 + num2; // 15
Or even:
const stringNum = "33.5"; const num = +stringNum; // 33.5 const result = num * 2; // 67
The ability to convert a string representing a number to an actual JavaScript number is hugely important for being able to process mathematical operations programmatically.
You can also increment a converted number:
let stringCount = "2"; let count = +stringCount; // 2 count++; // 3 console.log(count); // 3
Or use any other standard math operators (+, -, /, *, etc) on converted strings.
Conclusion
Converting strings to numbers is a common and necessary task in JavaScript. The main options for converting a string to a number are:
- The unary + operator: Simple but basic, no integer vs float distinction
- The Number() function: Handles whitespace better than + operator
- parseInt() and parseFloat(): Precisely convert to integer or float
When dealing with user input, make sure to trim whitespace and handle invalid entries as well.
The ability to convert strings to numeric data types opens up many possibilities for processing and manipulating values in your code. Mastering the various techniques for string to number conversion will serve you well!