styler
styler

Reputation: 16501

Having trouble building a calculator

I am trying to build a simple calculator to learn javascript/jquery but seem to be getting quite confused on how to make it work. Basically at the moment I dont seem to be able to update my tally correctly, instead of the numbers/values being added together in a sum they are being concatenated instead, if anyone could give me some guidance on how I can get back on the right path with this and any other advice on how to make the code more efficient then that would be great. I don't want anyone to give me the correct script just yet.

http://jsfiddle.net/kyllle/edRk9/4/

Thanks all in advance for your advice

Upvotes: 2

Views: 127

Answers (2)

FishBasketGordo
FishBasketGordo

Reputation: 23142

The val() method returns a string, and the + operator will concatenate if one of the operands is a string. You can convert the value to a number using parseInt[MDN]:

$('input.num', '#buttons').on('click', function() {
    // when click a number it appears in #result        
    currentNumber = parseInt($(this).val(), 10);
    $('#result').html(currentNumber);
});

Note, for parsing decimal numbers, use parseFloat[MDN], not parseInt.

Upvotes: 3

Alex Dn
Alex Dn

Reputation: 5553

parseInt, parseFloat or multiply value by 1 before sum or use eval(), but it's the worst case :)

Upvotes: 1

Related Questions