var num1 = '20',
num2 = '30.5';
Whenever you see the value into ” sign. So this is not number, this is string.
JS
var num1 = '20',
num2 = '30.5';
var sumN = num1 + num2;
document.getElementById("demo").innerHTML = sumN
HTML
<div id="demo"></div>
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”gxYyJK” default_tab=”result” user=”pradeepanvi”]See the Pen sum string in javascript test by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
So the answer will be like 2030.5, and we want that should be 50.5, For we need to convert string into number.
There is many options.
First is the unary plus operator to convert them to numbers first. Just add + sign before variable.
Second ParseInt Method.
var num1 = '20',
num2 = '30.5';
var sumN = +num1 + +num2;
var sumN2 = parseInt(num1 + num2);
//unary plus operator
document.getElementById("demo").innerHTML = sumN;
//parseInt method
document.getElementById("demo2").innerHTML = sumN;
HTML
<div id="demo"></div> <div id="demo2"></div>
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”wqwbwR” default_tab=”result” user=”pradeepanvi”]See the Pen sum string in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]