Calculate values in real R$

Asked

Viewed 23,957 times

6

Could someone help me calculate the values in cents, transform the value 1.6 in 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>

  • Did it all work out? It worked?

3 answers

12

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 don’t have to worry about decimal separator (whether it will be a comma or a dot) or concatenating the dollar sign (R$). Also if you need to show values in other currencies just change the location.

The method toLocaleString is old in browsers, what is new is the internationalization implementation. The table below shows which support the localization 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 return "1.6" to the code below (passing the parameters does not give error, only are ignored):

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

According to MDN, you can check if your browser supports internationalization options 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 proper support, you can rewrite the function toLocaleString, in a way able to understand currency format as follows (or as best suits you):

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 on MDN or in the MSDN:

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

  • Could you increase your response to contemplate cross-browser/server-side compatibility details of this solution? Very interesting, completely unaware of these parameters of toLocaleString!

  • 2

    I improved my answer by explaining better the question of compatibility and how to deal with it.

1

Use this solution. In addition to the two decimal places and the R$, it also applies points to each block of 3 numbers. It also does not depend on external libs. Outside it uses only one line and is fully functional. Vanilla :D

const centavosParaReais = centavos => 'R$ ' + (centavos / 100).toFixed(2).replace('.', ',').split('').reverse().map((v, i) => i > 5 && (i + 6) % 3 === 0 ? `${v}.` : v).reverse().join('')

0

Just replace:

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

For:

$("#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)

  • 1

    If the browser culture is not en 1.60 instead of 1,60

  • 1

    Need to negative my post? kkkkk!

  • I have already dispegatively, before you comment, really the solution works for most cases

  • Using comma: 'R$ ' + (+numero).toFixed(2).replace('.', ',')

  • 2

    I think it’s no use working for most cases, it has to work for all cases.

Browser other questions tagged

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