Javascript adding numbers as strings

前端 未结 4 802
深忆病人
深忆病人 2020-12-22 10:57

I have the following code which interprets the numbers as strings and adds them like 100300 instead of 400:

var rate = document.getElementById(\'pur_price\')         


        
相关标签:
4条回答
  • 2020-12-22 11:06

    Use function parseInt() it can be:

    document.getElementById('avg_claim_rate').value=id;
    document.getElementById('amount_claim').value=parseInt(pprice)+refurb;
    
    0 讨论(0)
  • 2020-12-22 11:09
    var result = +pprice + + refurb;
    
    0 讨论(0)
  • 2020-12-22 11:17

    As @sergio said, you can use JavaScript's built in parseInt function. Just for reference, you can multiply it by one. JavaScript always converts a string to a number if you multiply it. So you could do something like this:

    var num1 = "300";
    var num2 = "100";
    
    var num1 = num1 * 1; // Converts string to the number 300
    var num2 = num2 * 1;
    
    document.getElementById('number').value = num1+num2;
    <input id="number"/>

    This is just an alternate way to do the same thing. Use whatever is easiest for you. Hope that helps!

    0 讨论(0)
  • 2020-12-22 11:25

    You can use parseInt function:

    var pprice = parseInt(document.getElementById('pur_price').value, , 10);
    var rate1 = parseInt(document.getElementById('select2').value, , 10);
    
    0 讨论(0)
提交回复
热议问题