Ste
Ste

Reputation: 1520

Jquery math sum method

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

Answers (7)

Jamiec
Jamiec

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

RiaD
RiaD

Reputation: 47619

var sum=0;
$('div').each(
    function(){
         sum+=Number($(this).html());
    }         
);
alert(sum  );

Don't forget convert numbers to coreect format

Upvotes: -2

jensgram
jensgram

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

Alnitak
Alnitak

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

Ashwani K
Ashwani K

Reputation: 7980

Use following code

   var sum=0;
    $('div').each(function(){
    sum+=parseFloat($(this).text().replace(',','.');
    });

Upvotes: 1

Igor Dymov
Igor Dymov

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

abhijit
abhijit

Reputation: 1968

var sum = 0;
$('div').each(function() {
sum += $(this).text();
});
alert("The sum is "+ sum);

Upvotes: 1

Related Questions