How to get 2 decimal places [duplicate]

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 " 00,23 " discount, it shows the percentage value of "0.22999999999999998"% or if I inform you a discount percentage of " 03,4 "% it shows me the real discount of " 3,4000000000000004 " R $, I only want 2 decimal places after the comma.

    
asked by anonymous 02.09.2017 / 16:05

2 answers

1

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

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

Result: 0.23

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

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

Result: 0.23

  

If you already have a number in the format "0.23333", 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 the JS, the comma in a number represents separation of thousands, and   not of decimal place. Therefore, a number 0.23333 should be treated as type string , not as type number .

    
02.09.2017 / 16:18
1

To be two decimal places, you only need to put .toFixed(2) after the value received.

    
02.09.2017 / 16:16