Add real Brazilian currency div

Asked

Viewed 2,375 times

6

The script is adding up, but only numbers. I would like to have the values with dots and commas.

For example: 1,000,00 + 100,00 = 1,100,00

Somebody give that strength?

Follow the code below:

<script src="jquery_somar.js"></script>

<div class="somar">1.000,00</div>
<div class="somar">1.000,00</div>
<div class="somar">1.000,00</div>
<div id="resultado">3.000,00</div>

<script type="text/javascript">
    var sum = 0;
    $('.somar').text(function(i, v) {
        sum += parseFloat(v.replace(',', '.'));
    });
    $('#resultado').text('resultado : ' + sum);
</script>

2 answers

8


You can use the toLocaleString() to format the result. It will automatically adopt the way of showing the country that is configured on the computer. But if you want to force Brazil you can do so: .toLocaleString('pt-BR').

If you want to force two decimal places on the result, to give 3.000,50 in time of 3.000,5 you can use a second argument like I did in the example below:

So the code could be:

var total = $('.somar').get().reduce(function(tot, el) {
    var numero = el.innerHTML.split('.').join('').split(',').join('.');
    return tot + Number(numero);
}, 0);
$('#resultado').html(total.toLocaleString(undefined, {minimumFractionDigits: 2}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="somar">1.000,00</div>
<div class="somar">1.000,50</div>
<div class="somar">1.000,00</div>
<div id="resultado"></div>

jsFiddle: https://jsfiddle.net/3gsgyhs0/3/

  • I ran your code and that 3,000.5 in the answer can be problematic, because I think the ideal would be to put the extra zero that is missing in the pennies. Also, in the end he used comma as a thousands separator and dot to separate the whole part from the fractional. Anyway, keep my +1 also because of .toLocaleString('pt-BR') and of reduce.

  • @Victorstafusa the question of 3,000.5 not having zero at the end depends on the .toLocaleString(). Once we use it we have to believe that it will give the right result in each country.

  • Well, on second thought, I think it’s because my locale must be wrong (which would also explain a lot of bizarre things that just happen to me on other sites). This suggests that always use the 'pt-BR' and ignoring the browser locale would be nice.

  • @Victorstafusa I get en-US when I do window.navigator.userLanguage || window.navigator.language;

  • I tried to fix my browser configuration and tried to play your example using toLocaleString('pt-BR'). Gave as an answer "3.000,5". Then all that is needed is to fix the zero that is missing. Despite this, it continues to give to me en-US also.

  • @Victorstafusa discovered that one can pass a second argument .toLocaleString(undefined, {minimumFractionDigits: 2} and so forces two decimal places: https://jsfiddle.net/3gsgyhs0/3/

  • 1

    Excellent. If I were the OP I would accept your answer then. Just left to say that the undefined is the locale in case you don’t want to force the pt-BR or some other.

  • Perfect here worked out thank you very much for the strength of all you God bless, thank you very much solved !

  • @If the problem has been solved you can mark one of the answers as accepted. If you don’t know how to do it take a look here: http://meta.pt.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-reply

Show 4 more comments

4

Tell me what you think. The comments in the code explain how it works.

// Remove pontos, vírgulas, espaços e marcadores de moeda.
function limpar(x) {
    return x.replace(",", "").replace(".", "").replace("R$", "").replace(" ", "");
}

// Recebe um número inteiro (valor em centavos) e devolve uma string com o
// seu valor formatado como se fosse um valor monetário em real.
function formatarMoeda(numero) {

    if (isNaN(numero)) return "Valor não preenchido corretamente";

    // Descobre se o valor é negativo e extrai o sinal.
    var negativo = numero < 0;
    numero = Math.abs(numero);

    // Usado para produzir a resposta, caractere por caractere.
    var resposta = "";

    // Converte o número para string.
    var t = numero + "";

    // Itera cada caractere do número, de trás para frente.
    for (var i = t.length - 1; i >= 0; i--) {
        var j = t.length - i;

        // Adiciona o caractere na resposta.
        resposta = t.charAt(i) + resposta;

        // Colocar uma vírgula ou um ponto se for o caso.
        if (j == 2) {
            resposta = "," + resposta;
        } else if (j % 3 == 2 && i != 0) {
            resposta = "." + resposta;
        }
    }

    // Preenche os zeros a esquerda para o caso de o valor ser muito pequeno (menos de um real).
    if (resposta.length < 4) {
        resposta = "0,00".substring(0, 4 - resposta.length) + resposta;
    }
 
    // Coloca o sinal de negativo, se necessário.
    if (negativo) resposta = "-" + resposta;

    // Coloca como prefixo a unidade da moeda.
    return "R$ " + resposta;
}

function somar() {
    // Obtém os dois valores digitados.
    var a = parseInt(limpar($("#campo1").val()), 10);
    var b = parseInt(limpar($("#campo2").val()), 10);

    // Executa a soma.
    var soma = a + b;

    // Formata o resultado como moeda.
    var resposta = formatarMoeda(soma);
    $("#resultado").html(resposta);
}

$(document).ready(function() {
    $("#executar").click(somar);
    testes();
});

// Teste de unidade para a função formatarMoeda.
function testes() {
    var testar = [0, -1, -100, 100, 99, 10, 9, 4567, 567, 12345678910, NaN, "banana", undefined, "", "-"];

    var resultados = "Testes:";
    for (var e in testar) {
        resultados += "<br>[" + testar[e] + "] -> [" + formatarMoeda(testar[e]) + "]";
    }

    $("#testes").html(resultados);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="text" id="campo1" value="R$ " />
    <input type="text" id="campo2" value="R$ " />
    <input type="button" id="executar" value="Somar" />
    <div>Resultado da soma: <span id="resultado"></span></div>
    <button name="reset" type="reset" class="btn btn-theme btn-lg">Limpar</button>
</form>

<div id="testes"></div>

Browser other questions tagged

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