# $calc

## Basic Usage

```handlebars
{{$calc "5 + 3"}}              {{!-- outputs: 8 --}}
{{$ "5 + 3"}}                  {{!-- shorthand syntax --}}
```

### Output Types

The function can return different types of values:

* Numbers: Mathematical calculations, statistical results
* Strings: Text manipulation results
* Arrays: Collection operations
* Booleans: Conditional evaluations
* Empty String: Returned for null/undefined values or errors

### Variable Interpolation

Use `{variableName}` syntax to reference context variables:

{% tabs %}
{% tab title="Template" %}

```handlebars
{{$calc "{price} * 1.2"}}      {{!-- outputs: 120 --}}
{{$calc "{user.age} + 5"}}     {{!-- outputs: 30 --}}
```

{% endtab %}

{% tab title="Data" %}

```json
{
  "price": 100,
  "user": {
    "age": 25,
    "name": "John"
  }
}
```

{% endtab %}
{% endtabs %}

### Storing Results

You can store calculation results for later use using the `$var` function:

{% tabs %}
{% tab title="Template" %}

```handlebars
{{$var "tax_amount" ($calc "{price} * 0.2")}}
{{!-- Later in the template --}}
Total with tax: {{$calc "{price} + {tax_amount}"}}
```

{% endtab %}

{% tab title="Data" %}

```json
{
  "price": 100,
  "tax_rate": 0.2
}
```

{% endtab %}
{% endtabs %}

### Formatting Options

#### Decimal Places

```
{{$calc "100 / 3" decimals=2}}  {{!-- outputs: 33.33 --}}
```

#### Custom Number Format (using [number formatter](https://docs.documint.me/help-and-resources/how-to-videos/formatting-tokens#format-numbers) patterns)

```handlebars
{{$calc "1234.5" format="0,0.00"}}  {{!-- outputs: 1,234.50 --}}
{{$calc "0.123" format="0.00%"}}    {{!-- outputs: 12.30% --}}
```

#### Error Handling

```
{{$calc "10/0" error="Division Error"}}  {{!-- outputs: "Division Error" --}}
```

## Function Reference

### Mathematical Functions

#### **Basic Arithmetic**

* Addition (+), Subtraction (-), Multiplication (\*), Division (/), Modulo (%)

```handlebars
{{$calc "5 + 3"}}              {{!-- addition: 8 --}}
{{$calc "5 - 3"}}              {{!-- subtraction: 2 --}}
{{$calc "5 * 3"}}              {{!-- multiplication: 15 --}}
{{$calc "15 / 3"}}             {{!-- division: 5 --}}
{{$calc "5 % 2"}}              {{!-- modulo: 1 --}}
```

#### **Advanced Math Functions**

* abs(x): Returns absolute value of x

```handlebars
{{$calc "abs(-5)"}}            {{!-- absolute value: 5 --}}
```

* max(...args): Returns largest value among arguments

```handlebars
{{$calc "max(1, 2, 3)"}}       {{!-- maximum value: 3 --}}
```

* min(...args): Returns smallest value among arguments

```handlebars
{{$calc "min(1, 2, 3)"}}       {{!-- minimum value: 1 --}}
```

* pow(base, exp): Returns base raised to exp power

```handlebars
{{$calc "pow(2, 3)"}}          {{!-- power: 8 --}}
```

* sqrt(x): Returns square root of x

```handlebars
{{$calc "sqrt(16)"}}           {{!-- square root: 4 --}}
```

* round(x): Rounds to nearest integer

```handlebars
{{$calc "round(3.7)"}}         {{!-- round: 4 --}}
```

* ceil(x): Rounds up to nearest integer

```handlebars
{{$calc "ceil(3.2)"}}          {{!-- ceiling: 4 --}}
```

* floor(x): Rounds down to nearest integer

```handlebars
{{$calc "floor(3.8)"}}         {{!-- floor: 3 --}}
```

### String Operations

* lower(str): Converts string to lowercase

```handlebars
{{$calc 'lower("HELLO")'}}     {{!-- lowercase: "hello" --}}
```

* upper(str): Converts string to uppercase

```handlebars
{{$calc 'upper("hello")'}}     {{!-- uppercase: "HELLO" --}}
```

* trim(str): Removes leading/trailing whitespace

```handlebars
{{$calc 'trim(" hello ")'}}    {{!-- trim whitespace: "hello" --}}
```

* concat(...args): Joins all arguments into single string

```handlebars
{{$calc 'concat("a", "b")'}}   {{!-- concatenate: "ab" --}}
```

* slice(str, start, end): Extracts portion of string

```handlebars
{{$calc 'slice("hello", 0, 2)'}} {{!-- slice string: "he" --}}
```

* replace(str, search, replace): Replaces first occurrence of search with replace

```handlebars
{{$calc 'replace("hello", "l", "w")'}} {{!-- replace: "hewlo" --}}
```

### Array Operations

* arr(...args): Creates array from arguments

```handlebars
{{$calc "arr(1, 2, 3)"}}       {{!-- create array: [1, 2, 3] --}}
```

* first(arr): Returns first element

```handlebars
{{$calc "first([1, 2, 3])"}}   {{!-- first element: 1 --}}
```

* last(arr): Returns last element

```handlebars
{{$calc "last([1, 2, 3])"}}    {{!-- last element: 3 --}}
```

* len(arr): Returns array length

```handlebars
{{$calc "len([1, 2, 3])"}}     {{!-- array length: 3 --}}
```

* join(arr, separator, finalSeparator): Joins array elements with optional custom separators

```handlebars
{{$calc 'join(["a","b"], ",")'}} {{!-- join array: "a,b" --}}
```

* split(str, separator): Splits string into array

```handlebars
{{$calc 'split("a,b", ",")'}}  {{!-- split string: ["a", "b"] --}}
```

* sort(arr): Returns sorted array

```handlebars
{{$calc "sort([3, 1, 2])"}}    {{!-- sort array: [1, 2, 3] --}}
```

* reverse(arr): Returns reversed array

```handlebars
{{$calc "reverse([1, 2, 3])"}} {{!-- reverse array: [3, 2, 1] --}}
```

### Statistical Functions

* avg(...nums): Calculates average of numbers

```handlebars
{{$calc "avg(1, 2, 3)"}}       {{!-- average: 2 --}}
```

* med(nums): Calculates median of array

```handlebars
{{$calc "med([1, 3, 2])"}}     {{!-- median: 2 --}}
```

* sum(nums, \[prop]): Sums array elements, optionally extracting property from objects

```handlebars
{{$calc "sum([1, 2, 3])"}}     {{!-- sum: 6 --}}

{{!-- Sum with object arrays --}}
{{$calc 'sum([{val: 1}, {val: 2}], "val")'}}  {{!-- sum of val property: 3 --}}
```

### Type Conversion

* str(val): Converts to string

```handlebars
{{$calc 'str(123)'}}           {{!-- to string: "123" --}}
```

* num(val): Converts to number

```handlebars
{{$calc 'num("123")'}}         {{!-- to number: 123 --}}
```

* bool(val): Converts to boolean

```handlebars
{{$calc 'bool(1)'}}            {{!-- to boolean: true --}}
```

### Complex Examples

#### Data Processing Pipeline

{% code overflow="wrap" %}

```handlebars
{{!-- Store processed data for later use --}}
{{$var "processed_data" ($calc 'join(sort(arr(concat(upper("hello"), ":", str(sum([1,2,3]))),concat(lower("WORLD"), ":", str(avg(2,4,6)))))," | ")')}}

{{!-- Output: "HELLO:6 | world:4" --}}
{{processed_data}}
```

{% endcode %}

#### Complex Conditional Calculation

```handlebars
{{$calc 'if(len({items}) > 0) then concat("Items: ", join(sort(arr(concat(upper(first({items})), "-", str(sum({values}))), concat(lower(last({items})), "-", str(avg({values})))) ), " | ")) else "No items available"   endif'}}
```

### Limitations and Safety Features

* Maximum number size: 1e15
* Maximum array length: 1000

### Best Practices

* Store intermediate calculations using $var for complex operations
* Use appropriate formatting options for consistent output
* Handle potential errors with the error option
* Break complex calculations into smaller parts
* Use meaningful variable names
* Consider performance with large arrays
* Validate user input before processing
* Use comments to document complex expressions
