Home >Web Front-end >JS Tutorial >How Can I Add Numeric Strings Instead of Concatenating Them in Programming?
Concatenating or Adding Strings as Numbers
In programming, combining two strings typically results in concatenation, meaning they are joined together. However, when working with numeric strings, you may encounter the issue of addition yielding an unexpected result. To address this, understanding how to force strings to be treated as numbers is crucial.
To convert numeric strings into numbers for addition, employ the unary plus operator ( ). For instance:
var num1 = '20', num2 = '30.5'; console.log(+num1 + +num2); // Output: 50.5
By prefixing the strings with ( ), they are coerced into numbers, allowing the addition to occur correctly. Hence, num1 becomes 20 and num2 becomes 30.5, resulting in their sum being 50.5.
The above is the detailed content of How Can I Add Numeric Strings Instead of Concatenating Them in Programming?. For more information, please follow other related articles on the PHP Chinese website!