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>
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 ofreduce
.– Victor Stafusa
@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.– Sergio
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.– Victor Stafusa
@Victorstafusa I get
en-US
when I dowindow.navigator.userLanguage || window.navigator.language;
– Sergio
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 meen-US
also.– Victor Stafusa
@Victorstafusa discovered that one can pass a second argument
.toLocaleString(undefined, {minimumFractionDigits: 2}
and so forces two decimal places: https://jsfiddle.net/3gsgyhs0/3/– Sergio
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 thept-BR
or some other.– Victor Stafusa
Perfect here worked out thank you very much for the strength of all you God bless, thank you very much solved !
– Hemerson Prestes
@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
– Sergio