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

153
Visualizações
Convert input number with commas into a number to perform calculations and then return the output with commas?

I am working on a function. The JavaScript function starts formating the input text field as soon as a user starts typing in a number. This is good so far. But, when I try to take that value to perform a simple calculation, I get Nan error. I am assuming, it is due to the commas. So, can I remove these commas from the input while parsing it into the computation? And, once, the value is calculated. I want to show it in the commas format as an output (Annual Salary).

  $('input.number').keyup(function(event) {

    // skip for arrow keys
    if (event.which >= 37 && event.which <= 40) return;

    // format number
    $(this).val(function(index, value) {
      return value
        .replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
  }); 

  function calculateSalary() {
    var salary = document.getElementById("salary").value;
    var years = document.getElementById("years").value;

    var annumSalary = salary * years;
    document.getElementById("annumSalary").value = Math.round(annumSalary);
  } 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label>Salary</label>
<input class="form-control number" name="salary" id="salary"  required/>
<br>
<label>Years</label>
<input class="form-control" name="years" id="years" value="" type="number" required/>
<br>
<label>Annual Salary</label>
<input class="form-control number" name="annumSalary" id="annumSalary" value="" type="number" readonly/>
<br>
<input type="submit" name="calculate" id="calculate" value="Calculate" onClick="calculateSalary()" />

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

0

To remove the commas from the string and convert from string to number:

const str = '123,456.78';
const num = parseFloat(str.replace(/,/g, ''));

To convert back to string with commas:

const formatted = new Intl.NumberFormat().format(num);
about 4 years ago · Juan Pablo Isaza Relatório

0

Dude, just add parseInt() when you get the value with the document.getElementById('salary').value And if you think the user will enter decimals, use parseFloat.

Usually parseInt() and parseFloat() will convert the string to numbers escaping (common) things like (,.etc)

PS: Also if you're using jQuery, use $('#salary').value to make it look simple.

$('input.number').keyup(function(event) {

    // skip for arrow keys
    if (event.which >= 37 && event.which <= 40) return;

    // format number
    $(this).val(function(index, value) {
      return value
        .replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    });
  }); 

  function calculateSalary() {
    var salary = parseInt(document.getElementById("salary").value);
    var years = parseInt(document.getElementById("years").value);

    var annumSalary = salary * years;
    document.getElementById("annumSalary").value = Math.round(annumSalary);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label>Salary</label>
<input class="form-control number" name="salary" id="salary"  required/>
<br>
<label>Years</label>
<input class="form-control" name="years" id="years" value="" type="number" required/>
<br>
<label>Annual Salary</label>
<input class="form-control number" name="annumSalary" id="annumSalary" value="" type="number" readonly/>
<br>
<input type="submit" name="calculate" id="calculate" value="Calculate" onClick="calculateSalary()" />

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