# JavaScript examples: numbers, math and money

> Run Custom Code snippets for tax, discounts, currency formatting, percentages, interest, distances and rounding, in plain JavaScript.

Source: https://tadabase.com/docs/workflows/numbers-math-money-snippets  
Status: Verified Nov 17, 2026. Checked against the current product

Snippets for a **Run Custom Code** step that calculate with the values of one record: line totals with tax, discounts, percent change, interest, distances and rounding. For how the step works, see [Run custom JavaScript in a workflow](https://tadabase.com/docs/workflows/running-custom-javascript).

> **Totals over many records:** To add up, average or count values across many records or list items, use the **Aggregate** action instead of code. It offers **Sum**, **Average**, **Smallest**, **Largest**, **Median**, **Count items** and **Count unique values**, and can group the results. See [Count, total and summarize with Aggregate](https://tadabase.com/docs/workflows/count-and-total-with-aggregate).

## Before you start

1. **Add the step** Add a **Run Custom Code** step to your workflow and leave **Language** set to **JavaScript**.
2. **Add the inputs** Under **Data to use in the code**, click **+ Add Input** once for each input the snippet lists. Type the name from the snippet in **Variable name** and choose where the value comes from, for example **Record Value (Source)** or **Custom Value**.
3. **Paste and test** Click the **Code** box to open the code editor, paste the snippet, and click **Run**. The **Response** tab shows what the code returned.
4. **Use the results** In a later step, open the value picker, choose **Step Data**, pick this step, and pick the key the snippet returned (for example `full_name`).

An input is available in the code as `$` followed by its variable name: an input named `first_name` is `$first_name`. Add every input a snippet uses; a name with no matching input stops the code with a "not defined" error.

> **Plain JavaScript only:** The code runs as plain JavaScript (ES2020 or later). There are no `Str`, `Num`, `Arr` or `DateTime` helper objects, so older examples that used them stop with an error. The step adds `returnData`, `fail`, `getLoggedInUser`, `getAppDetails`, `getAppVariable` and `getAppSecret`; see [Run custom JavaScript in a workflow](https://tadabase.com/docs/workflows/running-custom-javascript).

## Two helpers for this page

Values from inputs often arrive as text, sometimes with a currency sign or thousands separators. Paste these two functions at the top of your code; the snippets below that say "Uses: num, round" need them.

```js
// Read a number from text such as "1,234.50" or "$99"; blank or invalid -> 0
function num(value) {
  const n = Number(String(value ?? "").replace(/[^0-9.\-]/g, ""));
  return Number.isFinite(n) ? n : 0;
}

// Round to a number of decimal places (2 by default)
function round(value, places = 2) {
  const f = 10 ** places;
  return Math.round((value + Number.EPSILON) * f) / f;
}
```

`Math.round` and `toFixed` work on binary fractions, so a value such as 1.005 can round down. `round` adds a tiny correction for that. For payment APIs, keep amounts in whole cents.

## Line total with tax

```js
// Inputs: price, qty, tax_rate (Custom Value, for example 0.0875)
// Uses: num, round
const subtotal = num($price) * num($qty);
const tax = round(subtotal * num($tax_rate));

returnData("subtotal", round(subtotal));
returnData("tax", tax);
returnData("total", round(subtotal + tax));
```

## Format an amount as currency text

Builds the text by hand, so it does not depend on locale settings in the code sandbox. Change `"$"` and the separators for other currencies.

```js
// Input: amount   1234.5 -> "1,234.50"
// Uses: num
const n = num($amount);
const [whole, cents] = Math.abs(n).toFixed(2).split(".");
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");

returnData("amount_display", (n < 0 ? "-" : "") + "$" + grouped + "." + cents);
```

## Percent change between two numbers

```js
// Inputs: previous, current
// Uses: num, round
const prev = num($previous);
const curr = num($current);
const change = prev === 0 ? null : round(((curr - prev) / prev) * 100);

returnData("pct_change", change);
returnData("trend", change === null ? "n/a" : change > 0 ? "up" : change < 0 ? "down" : "flat");
```

## Convert between dollars and cents

```js
// Inputs: amount (dollars), amount_cents
// Uses: num, round
returnData("cents", Math.round(num($amount) * 100));   // whole cents, for payment APIs
returnData("dollars", round(num($amount_cents) / 100));
```

## Apply a percentage or flat discount

```js
// Inputs: subtotal, discount_type ("pct" or "flat"), discount_value
// Uses: num, round
const subtotal = num($subtotal);
const value = num($discount_value);

let discount = $discount_type === "flat" ? value : subtotal * (value / 100);
discount = Math.min(subtotal, Math.max(0, discount));   // never negative, never more than the subtotal

returnData("discount", round(discount));
returnData("total", round(subtotal - discount));
```

## Weighted average

Takes two lists (for example from earlier steps) or two comma-separated texts.

```js
// Inputs: scores, weights (two lists of the same length, or comma-separated text)
// Uses: num, round
const list = v => Array.isArray(v) ? v : String(v ?? "").split(",");
const scores = list($scores).map(num);
const weights = list($weights).map(num);

let total = 0, weightSum = 0;
scores.forEach((s, i) => {
  const w = weights[i] ?? 0;
  total += s * w;
  weightSum += w;
});

returnData("weighted_average", weightSum === 0 ? null : round(total / weightSum));
```

## Compound interest

```js
// Inputs: principal, rate (0.05 for 5%), years, periods_per_year (12 = monthly)
// Uses: num, round
const p = num($principal);
const r = num($rate);
const t = num($years);
const n = num($periods_per_year) || 12;

const amount = p * Math.pow(1 + r / n, n * t);

returnData("future_value", round(amount));
returnData("interest_earned", round(amount - p));
```

## Convert an amount with a rate you supply

The code does not fetch exchange rates. Store the rate in an App Variable or a record and pass it in as an input, and update it yourself.

```js
// Inputs: amount, rate (how many target-currency units one source unit buys)
// The rate is whatever you pass in: this does not look up live exchange rates.
// Uses: num, round
returnData("converted", round(num($amount) * num($rate)));
```

## Progress percentage without dividing by zero

```js
// Inputs: completed, total
// Uses: num, round
const done = num($completed);
const total = num($total);
const pct = total === 0 ? 0 : round((done / total) * 100, 1);

returnData("pct_complete", pct);
returnData("progress", pct >= 100 ? "done" : pct === 0 ? "not_started" : "in_progress");
```

## Distance between two map points

Straight-line (great-circle) distance, not driving distance.

```js
// Inputs: lat1, lng1, lat2, lng2
// Uses: num, round
const rad = d => d * Math.PI / 180;
const [lat1, lng1, lat2, lng2] = [$lat1, $lng1, $lat2, $lng2].map(num);

const a = Math.sin(rad(lat2 - lat1) / 2) ** 2 +
          Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(rad(lng2 - lng1) / 2) ** 2;
const miles = 3958.8 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

returnData("miles", round(miles));
returnData("km", round(miles * 1.609344));
```

## Round to the nearest 0.05, 0.25, 5 or 100

```js
// Inputs: value, step (for example 0.05, 0.25, 5 or 100)
// Uses: num, round
const step = num($step) || 0.05;

returnData("rounded", round(Math.round(num($value) / step) * step));
```

## Keep a number between a minimum and a maximum

```js
// Input: score   Keeps the value between 0 and 100
// Uses: num
returnData("score_clamped", Math.min(100, Math.max(0, num($score))));
```
