Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

308
Visualizações
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:

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}`);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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}`);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda