How to add two strings as if they were numbers?

I have two strings which contain only numbers:

``````var num1 = '20',
num2 = '30.5';
``````

I would have expected that I could add them together, but they are being concatenated instead:

``````num1 + num2; // = '2030.5'
``````

How can I force these strings to be treated as numbers?

I would use the unary plus operator to convert them to numbers first.

``````+num1 + +num2;
``````

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)
``````

``````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;
``````

try

``````var x = parseFloat(num1) + parseFloat(num2) ;
``````

``````var x = parseInt(num1) + parseInt(num2) ;
``````

http://www.javascripter.net/faq/convert2.htm

You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also

and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.

I've always just subtracted zero.

``````num1-0 + num2-0;
``````

Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.

If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.

``````const bigInt = require('big-integer')
``````

Here, you have two options to do this :-

1.You can use the unary plus to convert string number into integer.

2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc

.

Now I am going to show you here with the help of examples(Find the sum of two numbers).

Using unary plus operator

``````<!DOCTYPE html>
<html>
<body>

<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
``````

Using parsing approach-

``````<!DOCTYPE html>
<html>
<body>

<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
``````
``````function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
``````

You can use `parseInt` to parse a string to a number. To be on the safe side of things, always pass `10` as the second argument to parse in base 10.

``````num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
``````

Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.

For example 5 - 7.6 = -2.5999999999999996

Use the `parseFloat` method to parse the strings into floating point numbers:

``````parseFloat(num1) + parseFloat(num2)
``````

I use this in my project.I use + sign to treat string as a number (in with_interesst variable)

``````<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest =   PHP"+with_interesst;
}
</script>

<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000"  onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
``````

Hope it helps

@cr05s19xx suggested on a duplicate question:

JavaScript is a bit funny when it comes to numbers and addition.

Giving the following

'20' - '30' = 10; // returns 10 as a number '20' + '30' = '2030'; // Returns them as a string The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:

``````function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;

console.log(output);

document.getElementById('demo').innerHTML = output;
}

function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;

console.log(output);

document.getElementById('demo1').innerHTML = output;
}
``````

You may use like this:

``````var num1 = '20',
num2 = '30.5';

``````

When apply *1 in num1, convert string a number.

if num1 contains a letter or a comma, returns NaN multiplying by 1

if num1 is null, num1 returns 0

kind regards!!!

Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.

``````    Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />

<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
``````

for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html

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'));
}
``````
``````document.getElementById(currentInputChoosen).value -= +-100;
``````

Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.

Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.

Don't know if it is a dirty workaround, or actually legit.