> For the complete documentation index, see [llms.txt](https://docs.eximee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/podstawy-pracy-ze-skryptami/operacje-matematyczne-w-scriptcode.md).

# Mathematical operations on numbers

The JavaScript environment (in which scripts are executed by default) natively uses a 64-bit floating-point format to store all numbers. This leads to well-known precision loss problems during simple calculations.

To completely eliminate this phenomenon, it is recommended that **all mathematical operations** – and in particular financial, tax, and currency calculations – be performed exclusively using the global object `BigDecimal`. It guarantees absolute calculation accuracy regardless of the complexity of the fractions.

## API interface definitions

### BigDecimal

Interface `BigDecimal` is the foundation of precise calculations in the Eximee system. It is an abstraction representing decimal numbers of arbitrary precision, which makes it possible to completely eliminate rounding errors known from the native type `Number` in JavaScript (the so-called IEEE 754 floating-point arithmetic phenomenon). This object is designed to be completely immutable, which makes it easier to track data flow and guarantees safety during complex calculations.

```javascript
interface BigDecimal {
  valueOf(value: string | number | BigDecimal): BigDecimal
  add(augend: string | number | BigDecimal): BigDecimal
  subtract(subtrahend: string | number | BigDecimal): BigDecimal
  multiply(multiplicand: string | number | BigDecimal): BigDecimal
  divide(divisor: string | number | BigDecimal): BigDecimal
  divide(divisor: string | number | BigDecimal, roundingMode: string): BigDecimal
  divide(divisor: string | number | BigDecimal, scale: number): BigDecimal
  divide(divisor: string | number | BigDecimal, scale: number, roundingMode: string): BigDecimal
  setScale(newScale: number): BigDecimal
  setScale(newScale: number, roudingMode: string): BigDecimal
  equals(equated: string | number | BigDecimal): boolean
  compareTo(compared: string | number | BigDecimal): int 
}
```

| Method                                     | Accepted arguments                               | Description                                                                                                         |                                                                                  |                                                    |                                                                                                                                     |
| ------------------------------------------ | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `valueOf(value)`                           | `string` \| `number` \| `BigDecimal`             | Creates and returns a new object `BigDecimal` based on the passed value.                                            |                                                                                  |                                                    |                                                                                                                                     |
| `add(augend)`                              | `string` \| `number` \| `BigDecimal`             | Adds the passed value and returns a new object with the result.                                                     |                                                                                  |                                                    |                                                                                                                                     |
| `subtract(subtrahend)`                     | `string` \| `number` \| `BigDecimal`             | Subtracts the passed value and returns a new object with the result.                                                |                                                                                  |                                                    |                                                                                                                                     |
| `multiply(multiplicand)`                   | `string` \| `number` \| `BigDecimal`             | Multiplies by the passed value and returns a new object with the result.                                            |                                                                                  |                                                    |                                                                                                                                     |
| `divide(divisor, [scale], [roundingMode])` | <p><code>string</code>                           | <code>number</code>                                                                                                 | <code>BigDecimal</code><br>(optional)\*: <code>scale</code>: <code>number</code> | <code>roundingMode</code>: <code>string</code></p> | Divides by the passed value. Optionally allows specifying the target scale and rounding mode. Returns a new object with the result. |
| `setScale(newScale, [roundingMode])`       | `newScale`: `number` \| `roundingMode`: `string` | Sets a new scale (number of decimal places), optionally applying the specified rounding mode. Returns a new object. |                                                                                  |                                                    |                                                                                                                                     |
| `equals(equated)`                          | `string` \| `number` \| `BigDecimal`             | Returns a boolean value (`true`/`false`) indicating whether the values are equal.                                   |                                                                                  |                                                    |                                                                                                                                     |
| `compareTo(compared)`                      | `string` \| `number` \| `BigDecimal`             | Compares values. Returns: `1` (greater), `0` (equal) or `-1` (less).                                                |                                                                                  |                                                    |                                                                                                                                     |

### DecimalFormat

Interface `DecimalFormat` serves as a bridge between strict mathematical logic and the user interface. It provides reliable mechanisms for two-way data conversion. On one hand, it allows formatting objects `BigDecimal` into readable strings (taking into account currencies, percentages, and local thousands and decimal separators), and on the other – safely parsing raw text from form fields back into useful mathematical objects.

```javascript
interface DecimalFormat {
    of(pattern: string): DecimalFormat
    of(pattern: string, symbols: DecimalFormatSymbols): DecimalFormat
    format(value: BigDecimal): string
    parse(value: string): BigDecimal
}
```

| Method                   | Accepted arguments                                                                            | Description / Return type                                                                               |
| ------------------------ | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `of(pattern, [symbols])` | <p><code>pattern</code>: <code>string</code><br><em>(optional)</em>: <code>symbols</code></p> | Initializes and returns a new formatter based on the pattern and an optional symbol (e.g. region `PL`). |
| `format(value)`          | `value`: `BigDecimal`                                                                         | Formats a mathematical object into readable text (`string`).                                            |
| `parse(value)`           | `value`: `string`                                                                             | Converts text entered by the user back into an object `BigDecimal`.                                     |

### Helper objects

This group collects enumeration types and utility interfaces that work closely with the mathematical operations and business logic of the application.

* Type `RoundingMode` gives the programmer absolute control over rounding algorithms when truncating fractional scale.
* Type `DecimalFormatSymbols` makes it easy to quickly adapt the numerical format to the specifics of the selected region (e.g. Polish commas vs English dots).
* Object `Random` provides a safe and standardized generator of unique identifiers (UUIDs), necessary when dynamically creating data packages.

```javascript
enum RoundingMode { UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN }

enum DecimalFormatSymbols { PL, EN, ES, SK, CZ }

interface Random {
    uuid(): string
}
```

## Working with the BigDecimal object

### Creating an object (Initialization)

The safest way to initialize a value is to use the method `valueOf()` and pass the number as text (`String`). This guarantees that the JavaScript engine will not introduce a precision error before the object is created.

```javascript
let value = BigDecimal.valueOf("10.1000"); // Definitely recommended approach
```

{% hint style="warning" %}
**Immutability** Object `BigDecimal` is immutable by design. Operations such as `add()` or `divide()` calculate a result and always return a completely **new** object. It is a mistake to call a method without assigning the result back to a variable.
{% endhint %}

### Examples of mathematical operations

**Addition and subtraction**

```javascript
let value = BigDecimal.valueOf("100.50");
value = value.add("5.25");      // Result: 105.75
value = value.subtract("5.75"); // Result: 100.00
```

**Multiplication and division**

When dividing with a result that has an infinite decimal expansion (e.g. 10 divided by 3), providing only the divisor value will cause an error. In such cases, you should always provide the target scale and rounding mode.

```javascript
let value = BigDecimal.valueOf("100");
value = value.multiply("20"); // 100 * 20 = 2000

// Division with specified precision: 10 / 3 = 3.33334
let shared = BigDecimal.valueOf("10");
shared = shared.divide("3", 5, RoundingMode.UP); 
```

**Setting the scale and comparing**

When comparing amounts, you should not use the standard JavaScript operators (e.g. `==`), but rather the built-in object methods `equals` and `compareTo`.

```javascript
let value = BigDecimal.valueOf("10.1234");
value = value.setScale(2, RoundingMode.HALF_UP); // Truncates and rounds to: 10.12

let limit = BigDecimal.valueOf("10.50");
let isEqual = limit.equals("10.50"); // Returns: true
let comparison = limit.compareTo("5"); // Returns: 1 (the limit value is greater than 5)
```

## Rounding and result scales

### Rounding modes (RoundingMode)

Constants from the object `RoundingMode` allow full control over what happens to the least significant digits when dividing or truncating the scale.

| Mode        | Behavior description                                                                                                                   |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `HALF_UP`   | Rounds up if the decimal part ≥ 0.5 (standard mathematical rounding).                                                                  |
| `HALF_DOWN` | Rounds down if the decimal part ≤ 0.5.                                                                                                 |
| `HALF_EVEN` | The so-called "banker's rounding." Rounds to the nearest even number in the case of an exact half (0.5). Minimizes statistical errors. |
| `CEILING`   | Always increases the number toward positive infinity.                                                                                  |
| `FLOOR`     | Always decreases the number toward negative infinity.                                                                                  |
| `UP`        | Rounds away from zero (increases the absolute value of the number).                                                                    |
| `DOWN`      | Simply truncates (discards) unwanted decimal fractions, moving toward zero.                                                            |

### Preferred scales for operations

To avoid hidden data loss after several consecutive mathematical calculations, it is recommended to use the following result scale calculations:

| Operation                 | Recommended result scale                    |
| ------------------------- | ------------------------------------------- |
| Add (Addition)            | `max(addend.scale(), augend.scale())`       |
| Subtract (Subtraction)    | `max(minuend.scale(), subtrahend.scale())`  |
| Multiply (Multiplication) | `multiplier.scale() + multiplicand.scale()` |
| Divide (Division)         | `dividend.scale() - divisor.scale()`        |
| Square root               | `radicand.scale() / 2`                      |

## Formatting data for display (DecimalFormat)

Object `DecimalFormat` is responsible for safe casting from a mathematical value to a textual representation (formatting) and from a textual representation to an object `BigDecimal` (parsing).

### Symbols in formatting patterns

| Symbol | Meaning                                                                                                                           |
| ------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `0`    | Placeholder for a digit. Forces zero to be displayed (e.g. creates leading zeros or fixed trailing zeros for cents).              |
| `#`    | Optional placeholder for a digit. It will be displayed only if the number contains it, hiding unnecessary zeros.                  |
| `,`    | Decimal separator or thousands grouping separator (translated accordingly depending on the locale, e.g. space or comma).          |
| `%`    | Multiplies the given value by 100 and appends the percent sign at the very end.                                                   |
| `E`    | Separates the mantissa from the exponent, forcing the number to be displayed in scientific (exponential) notation, e.g. `1.23E4`. |

### Examples of formatting and parsing

The following example generates the Polish number format.

```javascript
// Create a formatter for Polish with one decimal place enforced
let decimalFormatPL = DecimalFormat.of("#.0", DecimalFormatSymbols.PL);

// FROM OBJECT TO TEXT: Formatting ready to show the user
let stringValue = decimalFormatPL.format(BigDecimal.valueOf("34.567")); 
// Will return text: "34,6"

// FROM TEXT TO OBJECT: Parsing a value obtained e.g. from a form field
let decimalValue = decimalFormatPL.parse("34,6"); 
// Will return a technical object: BigDecimal(34.6)
```

## Additional tools (Random)

The API provides the class `Random` for generating random identifiers, useful, among other things, when populating data structures.

```javascript
function callService(context) {
    // Generating a globally unique, 128-bit UUID identifier (version 4)
    let uniqueId = Random.uuid();
    
    return [{ 'output': uniqueId }];
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.eximee.com/documentation/documentation-en/budowanie-aplikacji/logika-biznesowa/scriptcode/skrypty-scriptservice/api-skryptow/podstawy-pracy-ze-skryptami/operacje-matematyczne-w-scriptcode.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
