How to add two strings as if they were numbers?

2018-12-31 03:36发布

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?

标签: javascript
18条回答
美炸的是我
2楼-- · 2018-12-31 04:17

You can use this to add numbers:

var x = +num1 + +num2;
查看更多
初与友歌
3楼-- · 2018-12-31 04:20
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 ;
}
查看更多
余欢
4楼-- · 2018-12-31 04:22

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);
alert(num1 + num2);
查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 04:25

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

+num1 + +num2;
查看更多
余生请多指教
6楼-- · 2018-12-31 04:26

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;
}
查看更多
何处买醉
7楼-- · 2018-12-31 04:26

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

查看更多
登录 后发表回答