Adding Numbers and StringsJava uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.
When you "add" a number to a string the interpreter converts your number to a string and concatenates both together. When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur. When you then "add" a string "8" , string concatenation occurs again.
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0
is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats
with parseFloat(string)
or to integers
with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With