0

I am new to javascript. I'm trying to code a simple program which has 2 variables, each one contains an average number of some calculations, and using if else it should print the variable which contains the higher average as the winner.

without using toFixed() there is no problem, the higher variable is the winner and its printed out, but when I use toFixed(), it prints the lower variable, not the higher one. why is that? picture of the problem

here is the code:

const avgDolphins = ((96 + 108 + 89) / 3).toFixed(2);
const avgKoalas = ((88 + 91 + 911) / 3).toFixed(2);
console.log(`dolphins = ${avgDolphins} \nkoalas = ${avgKoalas}`)

if (avgDolphins > avgKoalas) {
    console.log(`Team Dolphins WON! with ${avgDolphins} Average score!`);
} else if (avgKoalas > avgDolphins) {
    console.log(`Team Koalas WON! with ${avgKoalas} Average score!`);
} else {
    console.log(`DRAW! Both teams got the same average score which is ${avgKoalas}`);
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    `toFixed()` returns a string which you're then comparing using the `>` operator. Save formatting like `toFixed()` for when you display values – Phil Feb 07 '22 at 23:25
  • Thank you so much. I used toFixed() when I display values and it worked :)) – Fadi aljohari Feb 07 '22 at 23:40

1 Answers1

1

Both .toPrecision(2) (Reference) and .toFixed(2) (Reference) will return a string. You can use a parseFloat arount your calculation to fix this.

So the resulting code will look like this:

const avgDolphins = parseFloat(((96 + 108 + 89) / 3).toFixed(2));
const avgKoalas = parseFloat(((88 + 91 + 911) / 3).toFixed(2));
console.log(`dolphins = ${avgDolphins} \nkoalas = ${avgKoalas}`)

if (avgDolphins > avgKoalas) {
    console.log(`Team Dolphins WON! with ${avgDolphins} Average score!`);
} else if (avgKoalas > avgDolphins) {
    console.log(`Team Koalas WON! with ${avgKoalas} Average score!`);
} else {
    console.log(`DRAW! Both teams got the same average score which is ${avgKoalas}`);
}
Kevin Glier
  • 1,346
  • 2
  • 14
  • 30