Home >Web Front-end >JS Tutorial >How Can I Add Strings Containing Numbers in JavaScript?
Combining Strings as Numbers
When attempting to combine strings containing numeric values, JavaScript treats them as text and concatenates them instead of performing mathematical operations. To rectify this issue, we can employ the unary plus ( ) operator to explicitly convert the strings to numbers prior to addition.
Consider the following example:
var num1 = '20'; var num2 = '30.5'; console.log(num1 + num2); // Outputs: '2030.5' (Concatenation)
To force JavaScript to treat these strings as numbers, we can use the unary plus operator as follows:
console.log(+num1 + +num2); // Outputs: 50.5 (Addition)
In this case, the unary plus operator converts both num1 and num2 to numbers before performing the addition operation. This approach ensures that JavaScript accurately interprets the strings as numeric values and calculates the desired result.
The above is the detailed content of How Can I Add Strings Containing Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!