# Setup Calculations

## What You'll Learn

In this tutorial, you'll build a quote summary that uses calculation tags to produce clean numeric and date output. By the end, you'll know how to:

* Calculate a deposit amount with `<MATH>`
* Calculate a remaining balance from the same source field
* Add days to a date with `type="date"`
* Use a calculation result inside conditional logic
* Prevent blank numeric fields from causing errors

## What You'll Build

An Opportunity quote summary that includes:

* The opportunity amount
* A 10% deposit amount
* A remaining balance
* A follow-up date 30 days after close
* A manager review note for larger deals

**Estimated time:** 15 minutes

## Prerequisites

Before starting, ensure you have:

* Access to S-Docs Templates in Salesforce
* Permission to create or edit templates
* An S-Docs template related to `Opportunity`
* A test opportunity with values in `Amount` and `CloseDate`
* Basic familiarity with merge fields such as `{{!Opportunity.Amount}}`

If you are brand new to S-Docs syntax, complete a basic merge field tutorial first.

{% hint style="info" %}
If you insert fields with the field picker, remove any auto-added number or date formatting before using those fields inside `<MATH>` tags.
{% endhint %}

{% stepper %}
{% step %}
**Step 1: Open or Create Your Template**

Start with an Opportunity template where you want to show calculated values.

1. Navigate to **S-Docs Templates** in Salesforce
2. Open an existing template or click **New Template**
3. Choose `Opportunity` as the related object
4. Open the template editor
5. Click **Source** if you want to paste the syntax directly

You now have a place to add calculation tags.
{% endstep %}

{% step %}
**Step 2: Add Your First Calculation**

Add a quote summary section with a 10% deposit calculation.

{% code title="deposit-example.html" %}

```html
<h2>Quote Summary</h2>
<p>Opportunity Amount: ${{!Opportunity.Amount}}</p>
<p>
  Deposit Due (10%):
  $<MATH format-number="#,###.00">{{!Opportunity.Amount}} * 0.10</MATH>
</p>
```

{% endcode %}

What you just did:

* Used `<MATH>` to multiply the opportunity amount by `0.10`
* Added `format-number="#,###.00"` for commas and two decimals
* Kept the original field visible for comparison
  {% endstep %}

{% step %}
**Step 3: Add the Remaining Balance**

Now calculate the amount left after the deposit.

{% code title="remaining-balance.html" %}

```html
<p>
  Remaining Balance:
  $<MATH format-number="#,###.00">
    {{!Opportunity.Amount}} - ( {{!Opportunity.Amount}} * 0.10 )
  </MATH>
</p>
```

{% endcode %}

What you just did:

* Subtracted the deposit from the full amount
* Used parentheses so the deposit is calculated first
* Kept spaces around operators so S-Docs reads the math correctly
  {% endstep %}

{% step %}
**Step 4: Add a Date Calculation**

Use a date calculation when you need a due date, reminder date, or follow-up date.

{% code title="follow-up-date.html" %}

```html
<p>
  Follow-Up Date:
  <MATH type="date" format-date="MMMM d, yyyy">
    {{!Opportunity.CloseDate}} + DAYS(30)
  </MATH>
</p>
```

{% endcode %}

What you just did:

* Started the expression with a date field
* Added `type="date"` so S-Docs treats the expression as date arithmetic
* Formatted the result as a readable date like `April 23, 2026`
  {% endstep %}

{% step %}
**Step 5: Use a Calculation Inside Conditional Logic**

You can evaluate a calculated result before showing a message.

Add this block below the quote summary:

{% code title="math-in-render.html" %}

```html
<!--RENDER=((<MATH>{{!Opportunity.Amount}} - ( {{!Opportunity.Amount}} * 0.10 )</MATH>) > 10000) -->
<p><strong>Manager review required.</strong> This deal exceeds the high-value threshold.</p>
<!--ENDRENDER-->
```

{% endcode %}

What you just did:

* Calculated the remaining balance inside the condition
* Compared that result to `10000`
* Rendered the note only when the threshold is passed
  {% endstep %}

{% step %}
**Step 6: Make the Calculation Safe for Blank Values**

Blank numeric fields can cause `Invalid double` and related errors.

Use `replaceall` to substitute a blank value with `0`.

{% code title="null-safe-math.html" %}

```html
<p>
  Deposit Due (safe version):
  $<MATH format-number="#,###.00">
    {{!Opportunity.Amount replaceall=" ,0"}} * 0.10
  </MATH>
</p>
```

{% endcode %}

What you just did:

* Replaced a blank amount with `0`
* Protected the math expression from null-style numeric errors
* Created a pattern you can reuse with optional numeric fields
  {% endstep %}

{% step %}
**Step 7: Save and Test Your Template**

Now test the calculation output with a real opportunity.

1. Click **Save** in the template editor
2. Generate the template from an opportunity with `Amount` and `CloseDate`
3. Check the deposit, remaining balance, and follow-up date
4. Test again with a larger amount to trigger the manager review note

What to verify:

* The deposit shows 10% of the opportunity amount
* The remaining balance equals the amount minus the deposit
* The follow-up date is 30 days after close
* The manager review note appears only when the balance is above `10000`
  {% endstep %}

{% step %}
**Step 8: Try a DOCX Variation**

If your template format is DOCX, wrap the full math expression in square brackets.

{% code title="docx-math-example.txt" %}

```plaintext
[<math>{{!Opportunity.Amount}} * 0.10</math>]
```

{% endcode %}

What changed:

* The calculation uses bracketed Microsoft template syntax
* The full math block stays inside the brackets
* The same formula logic still applies
  {% endstep %}
  {% endstepper %}

## Common Issues and Solutions

<details>

<summary>Issue 1: "The result does not show commas or decimals"</summary>

Problem: The number calculates, but the output is not formatted.

Solution:

* Add `format-number` on the `<MATH>` tag itself
* Use a pattern like `#,###.00`
* Regenerate the document after saving the change

</details>

<details>

<summary>Issue 2: "I get an Invalid double error"</summary>

Problem: One of the numeric fields in the expression is blank.

Solution:

* Replace blank values with zero using `replaceall=" ,0"`
* Test the source record to confirm the numeric field has data
* Apply the same null-safe pattern to every optional numeric field in the calculation

</details>

<details>

<summary>Issue 3: "Date math fails with a date format error"</summary>

Problem: S-Docs does not recognize the first value in the expression as a date.

Solution:

* Make sure the expression uses `<MATH type="date">`
* Start the expression with a date field such as `{{!Opportunity.CloseDate}}`
* If you use a static value, format it as `yyyy-MM-dd`

</details>

<details>

<summary>Issue 4: "The subtraction result looks wrong"</summary>

Problem: The total does not match the expected deposit or balance.

Solution:

* Add parentheses around the inner calculation
* Keep spaces around operators like `+`, `-`, `*`, and `/`
* Test the deposit formula by itself before combining it with a second expression

</details>

<details>

<summary>Issue 5: "The manager review note never appears"</summary>

Problem: The conditional block stays hidden even for large deals.

Solution:

* Check the threshold value in the `RENDER` condition
* Confirm the calculation returns a number before the comparison
* Test the same calculation outside the conditional block first

</details>

## What You've Learned

Congratulations! You've built a template with calculation tags and learned:

✅ How to calculate a percentage with `<MATH>`\
✅ How to calculate a remaining balance from one field\
✅ How to add days to a date with `type="date"`\
✅ How to use a math result inside `RENDER` logic\
✅ How to prevent blank-value errors with `replaceall`

## Next Steps

Now that you've mastered the basics, you can:

### Expand Your Calculations

* Add tax, subtotal, or discount calculations
* Build date offsets for reminders and due dates
* Reuse the same calculation pattern in other template sections

### Combine with Other Features

* Add conditional messages with [Getting Started with Conditional Logic](/quick-start/template-building/conditional-logic-tutorial.md)
* Reuse queried values with [Creating Your First Named Query](/quick-start/template-building/creating-your-first-named-query-tutorial.md)
* Format related output with [Get Started with Template Attributes](broken://spaces/v7v0UNK83URKB2C83QVU/pages/cHcfHnHS5o7uaK0xZNKt)

### Practice More

* Add a late-fee calculation to an invoice template
* Show approval language only above a calculated threshold
* Build due-date logic for contract follow-up steps

## Practice Exercise

To reinforce what you've learned, build an invoice-style Opportunity template that includes:

1. A subtotal based on `Opportunity.Amount`
2. A 7% tax calculation
3. A final total that adds subtotal and tax
4. A payment due date 14 days after `CloseDate`
5. An approval note that appears only when the final total is greater than `25000`

Bonus challenges:

* Make every numeric field null-safe
* Add a second threshold message for totals above `50000`
* Convert one calculation to DOCX syntax


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.sdocs.com/quick-start/template-building/get-started-with-calculations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
