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

203
Visualizações
I'm comparing two variables in an IF statement but I'm getting wrong results

I tried this code and when running for the first time i clicked start and i got me the result "1 is smaller than 2" whick is right but after changing the first input to 10 and clicking start again, it still showed "10 is smaller than 2". Am I doing something wrong here?

<textarea type="number" id="one">1</textarea>
<textarea type="number" id="two">2</textarea>

<a href="#" onclick="start()">Start</a>

<p id="demo"></p>

<script>
function start() {
    var numberOne = document.getElementById('one').value;
    var numberTwo = document.getElementById('two').value;
    
    if(numberOne>=numberTwo) {
        document.getElementById('demo').innerHTML = numberOne + ' is bigger than ' + numberTwo;
    }
    else {
        document.getElementById('demo').innerHTML = numberOne + ' is smaller than ' + numberTwo;
    }
}
</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are comparing strings, not numbers.

use parseInt or parseFloat to convert it to a number.

var numberOne = parseFloat(document.getElementById('one').value);
about 4 years ago · Juan Pablo Isaza Relatório

0

Yes it is expected, input in DOM always string even if the type is number.

parse them to number first before comparing.


const intOne = parseInt(numberOne, 10);
const intTwo = parseInt(numberTwo, 10);


// compare them
if (intOne >= intTwo) {
  // do your thing
}

Edit: Update code by @Sebastian Simon suggestion

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