Sum between inputs value fails in certain cases

1

I can not add the values and put the mask correctly between the inputs.

For example, I'm adding the following values to each input:

  • Adhesion Value input: 1.300,44
  • Input 1 of Dependent Values : 1.300,44
  • Input 2 of Dependent Values : 80,80

And in the input of the Total Value will be put the sum of the value of all the inputs together.

With this current code, if I put 80,79 in Input 2 of Dependent Values , the value hits, but 80,80 does not hit. I do not know how to solve this.

MembershipValuescript:

functionmascara(o,f){v_obj=ov_fun=fsetTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function mreais(v) {
    v = v.replace(/\D/g, "") //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})$/, ",$1") //Coloca a virgula
    v = v.replace(/(\d+)(\d{3},\d{2})$/g, "$1.$2") //Coloca o primeiro ponto
    return v
}

Adhesion Value input:

<input type="text" id="txt1" name="adesao" class="form-control calcular" placeholder="R$" onkeypress="mascara(this,mreais)" onkeyup="calcular()">

Total Value script:

<script type="text/javascript">
function calcular() {
    var soma = $('.calcular').get().reduce(function(soma, el) {
        return (parseFloat(el.value.replace(/\./g, "").replace(",", "."), 10) || 0) + soma;
    }, 0);
    document.getElementById('result').value = soma;

    mascara(document.getElementById('result'), mreais);


}
</script>

Total Value input:

<input type="text" class="form-control" name="total" id="result" readonly>

Script of Dependent Values :

<script type="text/javascript">
var AddTableRow = function(el) {
    var tbody = $(el).closest('table').find('tbody');
    var row = tbody.find('tr:last').clone();
    var name = row.find('.calcular').attr('name');
    var index = parseInt(name.match(/usuarios\[(\d+)\]\[valordependente\]/)[1], 10) + 1;
    row.find('[name^="usuarios["]').each(function() {
        if (this.name) {
            this.name = this.name.replace(/^usuarios\[\d+\]/, "usuarios[" + index + "]");
        }
    });
    tbody.append(row);
};
</script>
    
asked by anonymous 21.12.2016 / 18:33

1 answer

2

This is a problem not only of JavaScript but of computing in general.

You can use the .toFixed method in your soma variable to normalize this.

function calcular() {
    var soma = $('.calcular').get().reduce(function(soma, el) {
        return (parseFloat(el.value.replace(/\./g, "").replace(",", "."), 10) || 0) + soma;
    }, 0);

    soma = soma.toFixed(2);

    document.getElementById('result').value = soma;
    mascara(document.getElementById('result'), mreais);
}

I did not test, but it should work!

    
21.12.2016 / 21:22