Calculate values in real R $

5

Can anyone help me calculate the values in cents, transforming the value 1.6 into 1.60 .

Code:

$(document).ready(function () {
    var $entrada = 0,
        $saida = 0,
        $total = 0;
    $.each($("td[name='entrada']"), function() {
        $entrada += parseFloat($(this).text().replace(",", "."));
    });
    $.each($("td[name='saida']"), function() {
        $saida += parseFloat($(this).text().replace(",", "."));
    });
    $total = $entrada - $saida;
    $("#totalEntrada").append("R$ " + $entrada);
    $("#totalSaida").append("R$ " + $saida)
    $("#totalGeral").append("R$ " + $total);
});
<body>
    <h2>ENTRADA</h2>
    <table width="198" border="1" id="table">
        <tr>
            <td width="39%">PRODUTO</td>
            <td width="12%">VALOR</td>
        </tr>
        <tr>
            <td>1</td>
            <td name="entrada">100,00</td>
        </tr>
        <tr>
            <td>2</td>
            <td name="entrada">100,00</td>
        </tr>
    </table>
    <h2>SAIDA</h2>
    <table width="196" border="1">
        <tr>
            <td width="39%">DESCRICAO</td>
            <td width="12%">VALOR</td>
        </tr>
        <tr>
            <td>SAIDA</td>
            <td name="saida">50,00</td>
        </tr>
    </table>
    <h2>TOTAL</h2>
<table border="1">
    <tr>
        <td>TOTAL ENTRADA</td>
        <td id="totalEntrada"></td>
    </tr>
    <tr>
        <td>TOTAL SAIDA</td>
        <td id="totalSaida"></td>
    </tr>
    <tr>
        <td>TOTAL GERAL</td>
        <td id="totalGeral"></td>
    </tr>
</table>
</body>
    
asked by anonymous 06.05.2015 / 02:06

2 answers

9

If you are using modern browsers, use toLocaleString :

var formato = { minimumFractionDigits: 2 , style: 'currency', currency: 'BRL' }
$("#totalEntrada").append($entrada.toLocaleString('pt-BR', formato));
$("#totalSaida").append($saida.toLocaleString('pt-BR', formato));
$("#totalGeral").append($total.toLocaleString('pt-BR', formato));

This way you do not have to worry about a decimal separator (if it's going to be a comma or period) or even concatenating the dollar sign (R $). Also if you need to show values in other currencies, just change the location.

The toLocaleString method is already old in browsers, what is new is the implementation of internationalization. The table below shows which support location parameters:

Recurso         Chrome  Firefox     Internet Explorer       Opera       Safari (WebKit)
Suporte básico  Sim     Sim         Sim                     Sim         Sim
Localização     24      29          11                      15          Não Suportado

In Internet Explorer, for example, in versions smaller than 11, the toLocaleString would return "1.6" for the following code (parameter passing does not give an error, only ignored):

var numero = 1.6;
var dinheiro = numero.toLocaleString("pt-BR", { minimumFractionDigits: 2 , style: 'currency', currency: 'BRL' });

According to the MDN, you can verify that your browser supports internationalization options by using the following function:

function toLocaleStringSupportsLocales() {
   var number = 0;
   try {
     number.toLocaleString('i');
   } catch (e) {
     return e​.name === 'RangeError';
   }
   return false;
}

So, if you determine that the browser does not have the proper support, you can rewrite the toLocaleString function, so that you can understand currency format as follows (or how best to answer):

if(!toLocaleStringSupportsLocales()){
    Number.prototype.toLocaleString = function(lingua, opcoes) {
        var numero = this.toFixed(2).replace(".", ",");
        if(!opcoes)
            return numero;

        if(opcoes.style == "currency")
            return "R$ " + numero;        
    }
}

Read more at MDN or MSDN :

Note: I do not recommend prefixing variables with $ when they are not references to jQuery elements.

    
06.05.2015 / 02:41
1

Replace only:

$("#totalEntrada").append("R$ " + $entrada);
$("#totalSaida").append("R$ " + $saida)
$("#totalGeral").append("R$ " + $total);

By:

$("#totalEntrada").append("R$ " +  Number($entrada).toFixed(2));
$("#totalSaida").append("R$ " +  Number($saida).toFixed(2));
$("#totalGeral").append("R$ " +  Number($total).toFixed(2));

If you want to increase to R$ 1,600 , just put toFixed(3)

    
06.05.2015 / 02:27