Answered by:
How to get the sum of array elements

Question
-
Hi all,
i was trying to get the sum of array values retrieved by a xml query, so i have used the following code:
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.loadXML(resultXml);
var m = doc.selectNodes("//q1:manualdiscountamount");
var totalLineItemDiscountAmount=0;
if(m!=null)
{
for(i=0;i<m.length;i++)
{
alert("manualdiscountamount"+m[i].text);
totalLineItemDiscountAmount+=m[i].text;
}
}
alert("the sum is:"+totalLineItemDiscountAmount);
but for some reason that i cannot understand, this code concatenate the elements !!!
could anybody please help me to modify THIS code so i can get the summation of array values
any help will be appreciated
thanks in advance
Monday, November 15, 2010 10:52 PM
Answers
-
totalLineItemDiscountAmount.toFixed(2)
http://www.w3schools.com/jsref/jsref_tofixed.asp
MSCRM Bing'd - http://bingsoft.wordpress.com Check out the CRM 4 to CRM 2011 JavaScript Converter Tool CRM Forum Guidance on how to Help Us Help You - Marked as answer by DavidJennawayMVP, Moderator Tuesday, January 4, 2011 12:28 PM
Tuesday, November 16, 2010 1:04 AMModerator
All replies
-
You need to convert the text into a float:
totalLineItemDiscountAmount += parseFloat(m[i].text);
Otherwise, as you've noticed, you'll be doing string concatenation.
--pogo (pat)Monday, November 15, 2010 11:11 PM -
Thanks alot guys, i've used parseFloat and it works, the parseDecimal don't !!
but what if i need to display numbers with fractions ??
for exampe if the summation is 15, i want to display it as 15.00
Tuesday, November 16, 2010 12:57 AM -
totalLineItemDiscountAmount.toFixed(2)
http://www.w3schools.com/jsref/jsref_tofixed.asp
MSCRM Bing'd - http://bingsoft.wordpress.com Check out the CRM 4 to CRM 2011 JavaScript Converter Tool CRM Forum Guidance on how to Help Us Help You - Marked as answer by DavidJennawayMVP, Moderator Tuesday, January 4, 2011 12:28 PM
Tuesday, November 16, 2010 1:04 AMModerator