# Perform Calculations

## What Are Arithmetic Functions?

Arithmetic functions in S-Docs allow you to perform mathematical calculations directly within your document templates. Instead of pre-calculating values in Salesforce formulas, you can dynamically compute results using static numbers, numeric fields, or even date values at the time of document generation.

## How Are They Used in S-Docs?

Arithmetic functions enable you to:

* **Perform calculations** with numeric fields from Salesforce records
* **Add, subtract, multiply, or divide** values inline
* **Calculate date differences** or project future dates
* **Apply conditional logic** based on calculated results
* **Format numbers and dates** for professional presentation

Common use cases include calculating totals, discounts, days until expiration, payment schedules, and dynamic pricing.

***

## Basic Arithmetic Syntax

To use arithmetic functions in your S-Docs templates, enclose your calculation within `<MATH>` tags.

### Static Numbers

html

```
<MATH>(2 + 1) / 3</MATH>
```

### Using Salesforce Fields

html

```
<MATH>( {{!Opportunity.Num1__c}} + {{!Opportunity.Num2__c}} ) / {{!Opportunity.Num3__c}}</MATH>
```

**Important:** S-Docs evaluates all functions using the standard mathematical order of operations (PEMDAS).

***

## Working With Negative Numbers

You can use negative numbers in your calculations, but be mindful of spacing to avoid confusion between subtraction and negative values.

### Correct Syntax

html

```
<MATH>3 - 2</MATH>
```

This clearly performs subtraction.

### Avoid This

html

```
<MATH>3 -2</MATH>
```

Without proper spacing, the operation may be misinterpreted.

***

## Formatting Numbers

To format calculation results with commas, decimals, or other number patterns, use the `format-number` attribute within the `<MATH>` tag.

html

```
<MATH format-number="#,###.##">{{!Opportunity.Amount}} - {{!Opportunity.ExpectedRevenue}}</MATH>
```

**Note:** When inserting numeric fields using the Insert Field button, S-Docs automatically adds number formatting to merge fields. Be sure to remove this formatting when using merge fields within arithmetic functions to avoid conflicts.

***

## Arithmetic Functions With Date Fields

S-Docs supports two main types of date calculations:

* Adding/subtracting time from a date (e.g., future-dating documents)
* Calculating time between two dates

Both require the `type="date"` attribute within your `<MATH>` tag.

**Important:** Static dates must follow the `yyyy-MM-dd` format (e.g., `2021-01-01` for January 1, 2021).

### Adding or Subtracting Time

To add or subtract days, months, or years from a date field:

html

```
<MATH type="date">{{!Opportunity.CloseDate}} + DAYS(30) - MONTHS(1) + YEARS(2)</MATH>
```

### Calculating Time Between Dates

To find the difference between two dates:

html

```
<MATH type="date">DaysBetween({{!Opportunity.createdByDate}}, {{!Opportunity.CloseDate}})</MATH>
<MATH type="date">MonthsBetween({{!Opportunity.createdByDate}}, {{!Opportunity.CloseDate}})</MATH>
<MATH type="date">YearsBetween({{!Opportunity.createdByDate}}, {{!Opportunity.CloseDate}})</MATH>
```

{% hint style="info" %}
Note: if you encounter the error:\
”ERROR:Incorrect format, first argument in date arithmetic should be a date”\
the field may not be a date field, is missing, or is a date-time field instead of a date field. Verify that all fields used in `<MATH>` tags with `type="date"` or date functions are date type only.
{% endhint %}

### Formatting Dates

To format date calculation results, use the `format-date` attribute:

html

```
<MATH type="date" format-date="M/dd/yyyy">{{!Opportunity.createdByDate}} + DAYS(30)</MATH>
```

**Note:** When using the Insert Field button for date fields, S-Docs automatically adds date formatting to merge fields. Remove this formatting when using date fields within arithmetic functions.

***

## Arithmetic Functions With Conditional Logic

You can use arithmetic functions within conditional logic (RENDER) statements. S-Docs processes the arithmetic before evaluating the condition.

html

```
<!--RENDER=((<MATH>{{!Opportunity.My_Num__c}} + {{!Opportunity.My_Num_2__c}}</MATH>) > 100) -->
The sum of my numbers is more than 100!
<!--ENDRENDER-->
```

### Rounding For Conditional Logic

By default, arithmetic results are evaluated without rounding in conditional logic statements. To force rounding, use the `format-number` attribute.

**Without Rounding (Evaluates to False):**

html

```
<MATH>2 / 3</MATH> == 0.67
```

Since 2/3 = 0.666666..., this condition is false.

**With Rounding (Evaluates to True):**

html

```
<MATH format-number="#,###.##">2 / 3</MATH> == 0.67
```

The `format-number` attribute rounds the result to 0.67, making the condition true.

***

## Handling Null Values in Math Tags

### Problem

When generating documents, you may encounter error messages like:

* `ERROR: Ending position out of bounds: 22 STACK`
* `Invalid double`

These errors typically occur when merge fields within `<MATH>` tags contain null values rather than numeric values.

### Solutions

{% stepper %}
{% step %}

#### Solution 1: Replace Null With Zero

Add the `replaceall` attribute to merge fields to replace null values with zero:

html

```
<MATH>{{!Opportunity.Amount replaceall=" ,0"}} + {{!Opportunity.CustomField__c replaceall=" ,0"}}</MATH>
```

This ensures that if a field is null, it's treated as 0 in the calculation.
{% endstep %}

{% step %}

#### Solution 2: Conditional Logic With Named Queries

Use conditional logic combined with named queries to check for data existence before performing calculations:

html

```
<!--{{!<LineItemsSOQL>
<class>none</class>
<queryname>myQuery1</queryname>
<soql>SELECT count(ID) cid from opportunity where accountid = '{{!Account.ID}}'</soql>
</LineItemsSOQL>}}-->

<!--{{!<LineItemsSOQL>
<class>none</class>
<queryname>myQuery2</queryname>
<soql>SELECT SUM(amount) total, SUM(customfield__c) reduce from opportunity where accountid = '{{!Account.ID}}'</soql>
</LineItemsSOQL>}}-->

<!--RENDER='{{!myQuery1.cid}} > 0' -->
<MATH>{{!myQuery2.total}} + {{!myQuery2.reduce}}</MATH>
<!--ENDRENDER-->
```

This approach:

1. First checks if any records exist
2. Only performs the calculation if records are found
3. Prevents null value errors by avoiding calculations when no data exists

**Note:** This solution also addresses the common "Invalid double" error message associated with null values in numeric fields.
{% endstep %}
{% endstepper %}

***

## DOCX Template Syntax

When using arithmetic functions in DOCX templates, follow these rules:

1. Use `<math>` or `<MATH>` tags (not case sensitive)
2. Enclose the entire function within **square brackets** (For DOCX templates, all dynamic content must be enclosed in square brackets)

### Examples

html

```
[<math>(2 + 1) / 3</math>]
[<math>( {{!Opportunity.Num1__c}} + {{!Opportunity.Num2__c}} ) / {{!Opportunity.Num3__c}}</math>]
```

***

## Best Practices

* **Remove auto-formatting:** When inserting fields via the Insert Field button, remove any automatic number or date formatting before using them in `<MATH>` tags.
* **Use proper spacing:** Include spaces around operators (especially minus signs) to ensure correct interpretation.
* **Format intentionally:** Apply `format-number` or `format-date` attributes at the `<MATH>` tag level, not within individual merge fields.
* **Test conditional logic:** When using arithmetic in RENDER statements, verify rounding behavior to ensure conditions evaluate as expected.
* **Handle null values:** Always account for the possibility of null values in numeric fields by using `replaceall` or conditional logic to prevent generation errors.

***

Arithmetic functions in S-Docs provide powerful, flexible calculation capabilities that enhance document automation and reduce the need for pre-calculated formula fields in Salesforce.


---

# 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/sdocs/advanced-template-logic/perform-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.
