A fast way to do sum calculation in XSLT

In general, SharePoint developers avoid XSLT because is limited, this also being the one of the reasons SharePoint 2013 has started to adopt more and more JavaScript. But this doesn’t mean is dead. It is still very powerful being extended with ddwrt functions. I remember one of the challenges in XSLT was to calculate the sum of one column, as starting with SharePoint 2010 numbers output contains commas. It took a while for me also to figure out how I can do this in fast and reliable way, but it turned out was not so complicated as I thought.

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal">
	<xsl:template match="/">
		<!-- Create a variable TotalAmount and set it to zero -->
		<xsl:value-of select="ddwrt:SetVar('TotalAmount', 0)" />
		<!-- Iterate through the rows and increase TotalAmount with current amount (commas are removed to allow number conversion) -->
		<xsl:for-each select="/dsQueryResponse/Rows/Row">
			<xsl:value-of select="ddwrt:SetVar('TotalAmount', number(translate(@Amount,',','')))" />
		<!-- Output the result -->
		<xsl:value-of select="ddwrt:GetVar('TotalAmount')" disable-output-escaping="yes" />

SetVar function is allowing me to create and modify a variable. So with each row included in for-each iteration, the total amount is increased and, at the end of the iteration, calling GetVar function will output the result. This should be fast enough and avoids other operations outside for-each tag. In general, I used at least one for-each declaration per data form web part as the purpose of it is anyhow to show data.

GetVar and SetVar functions are opening a whole word for more complex calculation. Using them I was able to create complicated reports based on SharePoint lists.