Calculate with comma and dot with Jquery

Asked

Viewed 215 times

-1

Personal as I calculate example 1.400 + 1.400 would like the result to be the following result = 2.800 and not 2.8 someone can help me there ?

  $('input[type="text"]').keyup(function(){
                var val = $($(this)).val().replace(',','.');
                $($(this)).val(val);
                $('#result').val(Number($('input[name="number_01"]').val()) + Number($('input[name="number_02"]').val()));
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
          <label for="">Peso 01: </label>
          <br>
          <input type="text" name="number_01" id="number_01"><br>
          <label for="">Peso 02: </label>
          <br>
          <input type="text" name="number_02" id="number_02"><br><br>
          <label for="">Resultado: </label>
          <br>
          <input type="text" name="result" id="result">
</form>

  • 1

    https://answall.com/questions/101773/como-fazer-c%C3%A1lculos-em-javascript-accepting-v%C3%Adrgula-para-separar-casas-decimais - This will help you a lot. It was a little research before and it was already solved. Cumps

1 answer

0


Try to make the modifications below in your code that will work as desired.

$('input[type="text"]').keyup(function(){
    //Receber os 2 valores, substituir vírgulas por ponto (replace) e converter para float (decimal)
    var num1 = parseFloat($('#number_01').val().replace(',','.'));
    var num2 = parseFloat($('#number_02').val().replace(',','.'));
    //Somar os valores digitados e exibir o resultado preservando 3 dígitos após o ponto
    $('#result').val((num1 + num2).toFixed(3));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
          <label for="">Peso 01: </label>
          <br>
          <input type="text" name="number_01" id="number_01"><br>
          <label for="">Peso 02: </label>
          <br>
          <input type="text" name="number_02" id="number_02"><br><br>
          <label for="">Resultado: </label>
          <br>
          <input type="text" name="result" id="result">
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.