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);

3 Answers 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

Sign up to request clarification or add additional context in comments.

6 Comments

I would also specify the radix, parseInt(pce, 10); just in case.
Don't forget to specify the radix.
@user2120124 actually he was first.
Nix was first by a few seconds actually.
the unary + operator would be another option, if you feel like being more concise, although it also more cryptic... +pce + +epbcac
|
0

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

1 Comment

Have proper radix while parsing int. for example parseInt(pce, 10);
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.