# Calculating Totals

There may be times when you want to calculate a subtotal or a total from values in your data and display the result in your finished document.

In some cases, a value for the total may be provided in your data and can be used in your template like any other field. In other cases, a total will need to be calculated within your template.

These examples make use of tables built with repeating rows denoted with <<rr_. For more information on repeating rows see Tables – Part One.

Each of these examples begins by creating a new variable to store the Total value and setting its initial value to 0 like so: <<\$Total=0>>. Note that this variable does not appear in the data file but is created and used within the template itself.

Example 1

This first example shows a simple two column table. We want to sum up the values in the second column and display this total at the end of the table.

A new variable \$Total is added before the table and set to 0, <<\$Total=0>>. We add each value of numberSteps to this total with the line: <<\$Total={\$Total+numberSteps}>>. Since this line is removed from the output, it can be put anywhere between <<rr_ and <<er_ and still work. Finally, we can display the total by referencing the \$Total variable we created.

Example 2

This example shows what an invoice template might look like. We want to sum up the amounts and create both a sub total and a grand total.

A new variable \$TotalCost is added before the table and set to 0, <<\$TotalCost=0>>. We first determine the amount for the product by multiplying the quantity by the unitCost and storing the result in the new variable \$Amount, <<\$Amount={unitCost*quantity}>>. We can then add this amount to our total, <<\$TotalCost={\$TotalCost+ \$Amount}>>. At the end of the table we can display the sub total by referencing the \$TotalCost variable, <<{numFormat(\$TotalCost, ‘\$#,###.00’)}>>. The numFormat() method is used here to format the \$TotalCost to currency format. Finally, we can determine the grand total by adding the \$TotalCost variable to the \$GST and postage variables.

Example 3

In this example we show how to create a Running Total.

A new variable \$RunningTotal is added before the table and set to 0, <<\$RunningTotal=0>>. We add each value of amount to the running total, <<\$RunningTotal= {\$RunningTotal+amount}>> and then display its current value in each row, <<{numFormat(\$RunningTotal, ‘\$#,###.00’)}>>.

## Feedback

Invalid Input

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam.

Sorry, this field will only accept letters and numbers, and not special characters, to limit spam.

Invalid Input

### Applies To

Docmosis-Java Tornado Cloud
Version(s) ALL ALL ALL