Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda