Reputation: 1520
I need to sum some money value, i have this html
<div class=''>54,44</div>
<div class=''>34,10</div>
<div class=''>44,00</div>
<div class=''>14,50</div>
How can i make an alert with the sum of these div text?? ( the right sum!! ;-) ) Many thanks!
Upvotes: 5
Views: 13445
Reputation: 136094
Firstly, its worthwhile putting a data-attribute on each div with the raw amount, devoid of any locale-specific formatting.
eg/
<div data-amount="55.44">54,44</div>
Then assuming these div's are identifiable you can simply do
var total = 0;
$('some-selector-for-your-divs').each(function(){
total += parseFloat($(this).data('amount'));
});
Edit: Duh! parseInt on monetery amounts fixed.
Upvotes: 8
Reputation: 47619
var sum=0;
$('div').each(
function(){
sum+=Number($(this).html());
}
);
alert(sum );
Don't forget convert numbers to coreect format
Upvotes: -2
Reputation: 31508
var sum = 0;
$('div').each(function() {
var val = $(this).text().replace(',', '.'); // Replace , with .
sum += parseFloat(val);
});
(demo)
Update
The base 10 thing was crap.
Upvotes: 0
Reputation: 339786
A comma isn't a legal decimal separator in Javascript, so you'll have to convert the commas into decimal points:
var sum = 0;
$('div').each(function() {
var v = $(this).text().replace(',', '.');
sum += parseFloat(v);
});
alert(sum);
Upvotes: 2
Reputation: 7980
Use following code
var sum=0;
$('div').each(function(){
sum+=parseFloat($(this).text().replace(',','.');
});
Upvotes: 1
Reputation: 16460
Add some class like money
(or use $("div")
selector) and do something like this:
var sum = 0;
$(".money").each(function(){
sum += parseFloat($(this).text().replace(",", "."));
});
alert(sum);
Upvotes: 11
Reputation: 1968
var sum = 0;
$('div').each(function() {
sum += $(this).text();
});
alert("The sum is "+ sum);
Upvotes: 1