Calculate, Javascrips, Jquery

Asked

Viewed 44 times

0

I have a script, which is calculating, only that it brings me an integer, ie, if I calculate the values: 15,20 + 2,36 + 20,36 it will calculate only the integers, will bring me the result without the decimal place.

<script>
    function calculatotal() {

        var valor = $('#Valor').val();
        var multa = $('#Multa').val();
        var juros = $('#Juros').val();
        var total = $('#Total').val();


        if (valor == "") valor = 0;
        if (multa == "") multa = 0;
        if (juros == "") juros = 0;
        if (total == "") total = 0;

        var adicao = parseFloat(valor) + parseFloat(multa) + parseFloat(juros);
         $('#Total').val(adicao);


    }

    $(document).ready(function () {
        $('#Valor, #Multa,#Juros,#Total').blur(function () {
            calculatotal();
        });
        calculatotal();
    });

    $(document).ready(function () {

        calculatotal(); // calcula imediatamente ao carregar a página
        $('#Valor, #Multa,#Juros,#Total')
            .blur(function () { calculatotal(); }) // calcula ao perder o foco
            .keyup(function () { calculatotal(); }); // calcula ao soltar a tecla


    });

</script> 

Can someone give me a hint?

  • Let me give you a hint: Javascript considers the American currency standard. The comma separates thousands and decimal points.

1 answer

1


If your project is bringing the decimal number with a comma instead of a dot, it goes from the error when calculating. A possible solution would be you replace the comma by dot and if it is coming as string just convert to float, and finally to show two decimal places equal currency you can use toFixed, If you want to show the total to the user with a comma instead of a dot since our default is a comma, replace it in the total variable. Below is an example:

var valor = '10.10';
var multa = '5,50';
var juros = '5,50';

valor = parseFloat(valor.replace(",", "."));
multa = parseFloat(multa.replace(",", "."));
juros = parseFloat(juros.replace(",", "."));

var total = valor+multa+juros;
total = total.toFixed(2);
total = total.replace(".", ",");
alert(total);

Browser other questions tagged

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