0

So, i'm adding 2 characters 4 levels together (hp, attack, strength and defense) and then comparing them. However I am having a problem. when the numbers are added together they're added together as a string so it outputs as follows. 9060951/99709940 instead of 246 (90+60+95+1)/308 (99+70+99+40). Here is what I am doing.

function calculate(player1, player2) {
 var total1 = player1.getTotal();
 var total2 = player2.getTotal();
 var differencePercentage;
 if(total1 > total2) {
 differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
 } else {
 differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
 }
 var percentage = differencePercentage;
 return percentage;
}
function Player(hp, attack, strength, defense) {
 this.hp = parseInt(hp);
 this.attack = parseInt(attack);
 this.strength = parseInt(strength);
 this.defense = parseInt(defense);
 this.getTotal = function() {
 var total = 0;
 total = hp + attack + strength + defense;
 return total;
 }
}

Why is this happening?

asked May 2, 2014 at 13:22

1 Answer 1

5

You are parsing the Ints into this.hp, this.attack etc. in your Player function but not into the getTotal function

Try this

this.getTotal = function() {
 var total = 0;
 total = this.hp + this.attack + this.strength + this.defense;
 return total;
}
answered May 2, 2014 at 13:26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.