# how to accumulate a decimal total in jQuery / Javascript

`````` \$('span[id*="lblAmt"]').each(function () {
\$(this).css(
'border', 'solid 1px green'
);

tot += \$(this).text();
});

``````

I've established that it loops the appropriate number of times inside the each( ).

But the total in the ALERT is wacky.

Do I need to convert the text( ) to a decimal or something or other?

How can I accumlate values like this inside the each:

415.66
434
320.17
.17

Thank you.

LVL 5
###### Who is Participating?

PluritechnicianCommented:
``````var tot = 0;
\$('span[id*="lblAmt"]').each(function () {
\$(this).css(
'border', 'solid 1px green'
);

tot += \$(this).text() * 1; // or tot += parseFloat( \$(this).text() )
});

``````
0

Web developerAuthor Commented:
Yeah...it was parseFloat that I needed, I think!

``````  \$('span[id*="lblAmt"]').each(function () {
tot += parseFloat(\$(this).text());
});
``````

0

Web developerAuthor Commented:
Thank you.
0

Commented:
Here is a test script that works with your example data of strings.

Essentially we use a variety of built in Javascript functions and we are sure to initialize tot to 0:
parseFloat: http://www.w3schools.com/jsref/jsref_parsefloat.asp
Math.Round: http://www.w3schools.com/jsref/jsref_round.asp

``````<script type="text/javascript">
//initialize tot to 0
var tot = 0;
// array of string values
var values=new Array("415.66","434","320.17",".17");
//loop through with parseFloat
for (var i=0;i<values.length;i++)
{
tot += parseFloat(values[i]);
}
// round to two decimal places
tot = Math.round(tot*100)/100;
//output tot, use .toFixed(2) if you want two decimal places to always show
</script>
``````

``````//initialize
var tot = 0;

\$('span[id*="lblAmt"]').each(function () {
\$(this).css(
'border', 'solid 1px green'
);
//parseFloat
tot += parseFloat(\$(this).text());
});

// round to two decimal places, use 1000 for 3 decimal places, etc. You must do this because of float values extreme decimal places.
tot = Math.round(tot*100)/100;

//output
``````
0

PluritechnicianCommented:
longer than * 1 but more explicit too...
0

Web developerAuthor Commented:
matthewstevenkelly:

Thank you for this additional info!

Tom
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.