Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – I have a problem using toFixed() in (if else)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`);
}

>Solution :

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}`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading