rd42
rd42

Reputation: 3594

javascript if if else logic

There is some sort of logic error in my code, but I'm not sure where.

  1. When the elapsed time goes from 00:07:59 to 00:08:00, the color switches back from yellow, which happens at 00:05:00.
  2. At 00:10:00 it turns from gray to red.

Something in my logic allows any time between 00:08:00 and 00:09:59 to satisfy the first condition which is to be less than 5.

   if (parseInt(this.minutes) < 5) {
       fontColor = "<Font class=\"Gray\">";
   } else if (parseInt(this.minutes) >= 5 && parseInt(this.minutes) < 10){
       fontColor = "<Font class=\"Yellow\">";
   } else {
       fontColor = "<Font class=\"Red\">";
   }

Upvotes: 0

Views: 96

Answers (2)

yoavmatchulsky
yoavmatchulsky

Reputation: 2960

This is a feature (not a bug!) in parseInt.

When the string starts with a 0, it parses it in Octals (base 8), instead of Decimals (base 10). just pass a second parameter of 10, and it will use that base for parsing.

if (parseInt(this.minutes, 10) < 5) {
    fontColor = "<Font class=\"Gray\">";
} else if (parseInt(this.minutes, 10) >= 5 && parseInt(this.minutes, 10) < 10) {
    fontColor = "<Font class=\"Yellow\">";
} else {
    fontColor = "<Font class=\"Red\">";
}

Upvotes: 4

jAndy
jAndy

Reputation: 235962

Even without knowing what is stored in this.minutes, my guess is that you get in trouble because of the missing radix value for parseInt().

Since you mentioned you got numbers starting with 0 this is very likely because parseInt assumes those as octal values.

So easy solution, set the radix to 10 to specify a decimal value:

if (parseInt(this.minutes, 10) < 5) {
}

Upvotes: 2

Related Questions