0

im having a problem adding these variables lets say 'pce'=100 and 'epbcac'=200 my result is 100200 instead of 300 what am i doing wrong thanks,

var pce = $('#pce').val();
var epbcac=$('#epbcac').val();

var results12 = pce + epbcac;

$('#tc').val(results12);
4

3 回答 3

4

You are adding strings. You need to make them ints parseInt(string, radix).

var results12 = parseInt(pce,10) + parseInt(epbcac,10);

As @Joe mentioned radix is optional, but if you dont specify it the browser could use a different radix and could cause unpredictable behavior.


Alternatively, as @DavidMcMullin suggested a Savvier way to do it is to use the unary + operator:

var results12  = +pce + + epbcac

Radix is the base of the number system. Meaning the numbers that make up the system:

Binary: radix=2
01010101

Decimal: radix=10
0123456789

Hex: radix=16
0123456789ABCDEF

于 2013-03-01T20:03:40.743 回答
0

Use parseInt(pce); and parseInt(epbcac); before summing it up.

于 2013-03-01T20:04:07.953 回答
0

As others said, use parseInt, but ideally use

parseInt(pce,10) + parseInt(epbcac,10)

otherwise strings with leading zeros in the form "012" will be parsed incorrectly as hex digits and the addition won't work correctly.

于 2013-03-01T20:07:52.813 回答