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);
Jayrok94
  • 129
  • 2
  • 9

3 Answers3

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

Community
  • 1
  • 1
Nix
  • 57,072
  • 29
  • 149
  • 198
0

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

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.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71