Home >Web Front-end >JS Tutorial >How Can I Perform Math on Strings in JavaScript?
Converting Strings to Numbers for Mathematical Operations
Despite containing numerical characters, strings cannot be directly manipulated as numbers. To perform arithmetic operations, it is necessary to first convert them into numerical form.
Consider the example given:
var num1 = '20', num2 = '30.5';
Adding these strings directly results in concatenation:
num1 + num2; // '2030.5'
To force them to be treated as numbers, use the unary plus operator ( ):
+num1 + +num2;
The unary plus operator coerces the strings into numerical data types before performing the addition, allowing for accurate mathematical operations:
+num1 + +num2; // 50.5
The above is the detailed content of How Can I Perform Math on Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!