How to take 2 decimal places

Asked

Viewed 4,846 times

1

How do I show only 2 decimal places after the comma.

I have the following script:

 <script>
    function DescontoPorcentagem() {
        var bruto = $("#tot_bruto").val();
        var porcentagem = $("#Tot_desc_prc").val();
        var real = $("#Tot_desc_vlr").val();
        var total;
        total = parseFloat((parseFloat(porcentagem) / 100) * parseFloat(bruto));

        $("#Tot_desc_vlr").val(parseFloat(total));
        total = parseFloat(bruto) - parseFloat(total);
        $("#tot_liquido").val(parseFloat(total));
    }

    function DescontoReal() {
        var bruto = $("#tot_bruto").val();
        var porcentagem = $("#Tot_desc_prc").val();
        var real = $("#Tot_desc_vlr").val();
        var total;
        total = parseFloat(bruto) - parseFloat(real)
        $("#tot_liquido").val(parseFloat(total));
        total = (real / bruto) * 100
        $("#Tot_desc_prc").val(total);
    }
</script>

If I have a value in the field "tot_bruto" of 100, and give a discount of "00,23"R$ it shows the value of the percentage of "0,22999999999999998"% or if I report a discount in percentage of "03,4"% he shows me the real discount of "3,4000000000000004"R$, I just want it to appear 2 decimal places after the comma.

  • Tries with .toFixed(2).

2 answers

1

For it to stay two decimal places you need to just put .toFixed(2) after the amount received.

1


With toFixed(n) you convert a number into a string with n decimal places.

var numero = 0.2333333;
numero.toFixed(2); // 2 casas decimais

Upshot: 0.23

JS works with decimal places separated by ".". If you want the result with a comma, then you need to replace the point:

numero.toFixed(2).replace(".",",");

Upshot: 0,23

If you already have a number in the "0.23333" format, you need to convert it before for "0.23333" for toFixed() to work.

valor = "0,2333333"; //string que representa o número
valor = valor.replace(",","."); //troco a vírgula por ponto
valor = parseFloat(valor); // converto em número
console.log(valor.toFixed(2).replace(".",",")); // converto em string de novo, com vírgula e 2 casas decimais

For JS, the comma in a number represents thousand separation, and not to one decimal place. Therefore, a number 0.23333 should be treated as a type string, and not as a type number.

Browser other questions tagged

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