Question:
The script is adding, but only numbers. I would like to have the values with dots and commas.
For example: 1000.00 + 100.00 = 1100.00
Does anyone give this strength there?
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>
Answer:
You can use toLocaleString()
to format the result. It will automatically adopt the country display way which is configured on the computer. But if you want to force Brazil you can do it like this: .toLocaleString('pt-BR')
.
If you want to force two decimal places in the result, to give 3.000,50
of 3.000,5
you can use a second argument as 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>