简体   繁体   中英

How to add two values in javascript

This is a simple dropdown with values. I'm trying to pull the values as currency then add.

The values aren't being added ( 1+1=2 or 1+2=3 ) but instead are concatenating ( 1+1=11 or 1+2=12 ). Where am I going wrong here?:

<script>
    function displayResult()
    {
        var strm=document.getElementById("matt").options[document.getElementById("matt").selectedIndex];
        var t=strm.text.search("\\\$");
        var strb=document.getElementById("box").options[document.getElementById("box").selectedIndex];
        var b=strb.text.search("\\\$");
        var x=strm.text.substr(t+1);
        var y=strb.text.substr(b+1);
        var math= x + y;

        alert(strm.text.substr(t+1));
        alert(strb.text.substr(b+1));
        alert(math);
    }
</script>

<form>
    Select #1:
    <select id="matt">
        <option>$1.00</option>
        <option>$2.00</option>
    </select>

    <br />
    Select #2:
    <select id="box">
        <option>$3.00</option>
        <option>$4.00</option>
    </select>

</form>

<button type="button" onclick="displayResult()">Display index</button>

Use parseInt() to cast your strings as integers.

var math= parseInt(x,10) + parseInt(y,10);

See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

To make sure your values are added as numbers, cast them to Number first:

Number('2') + Number('2') = 4
'2' + '2' = '22'

Try using parseFloat() or parseInt().. Otherwise it won't recognize it as a number.. It will append as a normal string..

var math= parseFloat(x) + parseFloat(y);

alert(math)

Check FIDDLE

这些值被解释为字符串,您需要在添加它们之前使用parseInt将它们转换为int。

The substring() function returns the substring of a given string, which is, of course, a string and not an object upon which math can be performed. If you parse those strings into a number, using parseInt() , then it will work:

var x= parseInt(strm.text.substr(t+1),10);
var y= parseInt(strb.text.substr(b+1),10);

Also, you don't need to keep redeclaring var , you could instead comma-separated variable declarations:

var x = parseInt(strm.text.substr(t+1),10),
    y = parseInt(strb.text.substr(b+1),10);

I discovered something interesting today. I was doing the calculator project on theodinproject. I have addition, subtraction, multiplication, and division functions. Subtraction, multiplication, and division works fine without needing to explicitly tell javascript to treat the parameter as a Number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM