0

So here's my code:

var score1 = $(this).attr('data-score1');
var score2 = $(this).attr('data-score2');

if (score1 < score2) {
  // do some
}
if (score2 > score1) {
  // do something else
}

Now, this works fine as long as both variables are either both < or both > 100, yet whenever either of those variable is larger than 100 while the other is not the wrong if statement gets triggered. What the hell could be going on here? Thanks for any advice!

6
  • 2
    @ÁlvaroG.Vicario You should make an answer. Commented Oct 29, 2012 at 18:02
  • Dont know this language, but it probably compares them as strings Commented Oct 29, 2012 at 18:02
  • "90" is greater than "100" because "9" has a higher ascii value than "1". Commented Oct 29, 2012 at 18:03
  • 1
    Just so you know, jQuery isn't a language. You're programming in JavaScript. Commented Oct 29, 2012 at 18:04
  • @Diodeus I'm not sure "ascii" is exact here. Commented Oct 29, 2012 at 18:04

2 Answers 2

7

Use parseInt()

The attributes will throw up strings.. So when you try to compare them... You are actually comparing

"100" > "90" and not 100 > 90 .. Using parseInt() with a radix should solve your problem..

var score1 = parseInt( $(this).attr('data-score1') , 10);
var score2 = parseInt( $(this).attr('data-score2') , 10);

if (score1 < score2) {
  // do some
}
else if (score2 > score1) {
  // do something else
}

As @naveen suggested you could do this as well

var score1 = +$(this).attr('data-score1');
var score2 = +$(this).attr('data-score2');
Sign up to request clarification or add additional context in comments.

8 Comments

dude, +$(this).attr('data-score1') will do
@webarto that would make it score1 >= score2
@webarto : there could be a tie
@naveen parseInt() is much more readable. If you go for shortness (for some reason), you can use + of course.
@naveen You might or might not know that in Javascript unary + converts to number. If you see parseInt(), you already know what it does. If not, you have a function name to search on. I mean, yes, it is very clever that you know this trick, but do you really want to use it in code that other people will read?
|
3

You're comparing the values as strings. The string "90" begins with 9, which has an ascii code that is greater than that of 1.

You can convert it to a number by using parseInt

parseInt(score1, 10)

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.