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

229
Visualizações
User input and toFixed method not working

I am trying to have a user input their number into an HTML input tag, and then have them click a button and output a fixed number with two decimal points. I am unable to get it to work even though I have followed examples and even copied what they did at points, not sure what I am doing wrong. I am pretty new to JavaScript so I don't quite understand what I am doing.

Html and its JS code are below:

HTML:

<p> Input below to fix your number </p>
    <input id="input1" type="number" placeholder="number 1">
    <button onclick="javascript:tofixed_method()">CLICK</button>
<p> Your fixed number: <span id="answer"></span></p>

JavaScript:

function tofixed_method() {
    var val1 = document.getElementById("input1").value;
    var val2 = val1.toFixed(2);
    document.getElementById("answer").innerHTML = val2;
}

Thank you!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

document.getElementById("input1").value gives you a string. You need to turn it into a number first, using parseInt for example:

function tofixed_method() {
  var val1 = document.getElementById("input1").value;
  var val2 = parseInt(val1).toFixed(2);
  document.getElementById("answer").innerHTML = val2;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can refer to the logic of rc-input-number.There are many factors to consider.

// '1.' '1x' 'xx' '' => are not complete numbers
function isNotCompleteNumber(num) {
  return (
    isNaN(num) ||
    num === '' ||
    num === null ||
    (num && num.toString().indexOf('.') === num.toString().length - 1)
  );
}

function tofixed_method() {
  const input_value = document.getElementById('input1').value;
  const input_num = parseFloat(input_value, 10);
  document.getElementById('answer').innerHTML = isNotCompleteNumber(input_num) ? '' : input_num.toFixed(2);
}
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