Add up repeating numbers using the Sum() function
To simply add up all the numbers inside a ForEach, you can use the Sum() function as demonstrated below:
«ForEach(Invoice_item)»
«position()». «Desc»: «FormatNumber(Amount)»
«End()»
TOTAL: «FormatNumber(sum(Invoice_item/Amount))»
«CaptureInGrid(Invoice_item,Yes)»
Using some XPATH, you can add on to the above code snippet and only sum certain parts inside the ForEach as per the following example:
«CaptureInGrid(Invoice_item,Yes)»
«ForEach(Invoice_item)»
Description: «Desc» «FormatNumber(Amount)»
This expense is paid by: «ChooseFromList(Parent,,Father,Mother)»«Parent»
«End()»
Total payable by Father: «FormatNumber(sum(Invoice_item[Parent = ‘Father’]/Amount))»
Total payable by Mother: «FormatNumber(sum(Invoice_item[Parent = ‘Mother’]/Amount))»
Something to note about the Sum() function, the calculation will break if you leave any of the numbers in the ForEach empty. To get the calculation to work successfully, the summing needs to happen over valid numeric values which can be guaranteed in a few ways.
- Make the data elements required.
- Make sure the data elements are numeric e.g. FormatNumber, Question command with type Number, CaptureDataElement(X,Decimal).
- Put a Rule on the data element.
- Set a value to 0 like this:
«Set(Amount,(Amount = ''),0)»
That goes inside the ForEach, and ensures that if the data element is blank it is assigned a value of 0.