JavaScript examples: numbers, math and money
Run Custom Code snippets for tax, discounts, currency formatting, percentages, interest, distances and rounding, in plain JavaScript.
- Verified Nov 17, 2026
- Classic builder
On this page
- Before you start
- Two helpers for this page
- Line total with tax
- Format an amount as currency text
- Percent change between two numbers
- Convert between dollars and cents
- Apply a percentage or flat discount
- Weighted average
- Compound interest
- Convert an amount with a rate you supply
- Progress percentage without dividing by zero
- Distance between two map points
- Round to the nearest 0.05, 0.25, 5 or 100
- Keep a number between a minimum and a maximum
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.
Before you start #
- Add the step Add a Run Custom Code step to your workflow and leave Language set to JavaScript.
- 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.
- 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.
- 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.
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.
// 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 #
// 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.
// 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 #
// 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 #
// 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 #
// 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.
// 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 #
// 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.
// 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 #
// 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.
// 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 #
// 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 #
// Input: score Keeps the value between 0 and 100
// Uses: num
returnData("score_clamped", Math.min(100, Math.max(0, num($score)))); Was this page helpful?
Something wrong or missing on this page? Tell us.