开发者

Addition problem, "integers" acting like strings

    var 
        calculator = document.calculator;
            input1 = calculator.input1;
     开发者_高级运维       input2 = calculator.input2;
            result = calculator.result;
            equals = calculator.equals;

    function add(a,b) {
     equals.value = a+b;
    }

    result.addEventListener("click", function() {
     add.apply(add, [input1.value, input2.value]);   
    });

<form name="calculator">
    <input type="text" name="input1" /><br />
    <input type="text" name="input2" /><br />
    <input type="button" name="result" value="result" /><br /><br />
    <input type="text" name="equals" readonly="true" />
</form>

It only returns the to numbers together -- not added. For example: 5 + 3 = 53 not 8. How do I fix this??


Use parseFloat(a) + parseFloat(b) if it's a float type or parseInt(a, 10) + parseInt(b, 10) for integer type.


Javascript will, by default, always interpret input as strings.

There are a few ways around this, by using the builtin parseXXX() functions or simply by first multiplying the values by 1 as recommended by this page.


The problem here is, your code is doing a string concat operation (using + on strings) on a and b.

You need to explicitly specify that, you want addition (using + on numbers) to be performed on a and b.

Change your add function to:

function add(a,b) {
     equals.value = Number(a) + Number(b);
}


This is simpler.

Just multiply the values of each input by 1 to convert them to number.

input1 = calculator.input1*1;
input2 = calculator.input2*1;

or subtract a zero

input1 = calculator.input1-0;
input2 = calculator.input2-0;

Note: Thanks Matthew for the tip ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜