Skip to content

Deterministic Financial Calculations in n8n: Rounding, Missing Inputs, Rule Versions and Test Fixtures

A calculation workflow is only trustworthy if the same input always gives the same answer and a bad input never becomes a confident number. A worked n8n Code node example with integer money, explicit rounding, rule versions and fixtures.

A mechanical adding machine feeds a rule-version paper tape with a rounding step circled in orange.
Runtime validation and calculation lead to output or rejection. A separate development lane runs fixtures through the same proposed calculation workflow and fails on mismatches.
Synthetic toy, not financial advice • fixtures do not run on customer requests

Text equivalent. Calculation workflows Teaching diagram • Validation, rounding and fixtures RUNTIME / EVERY REQUEST Validate + calculate Integer minor units rule_version Status = ok? Half-up to 0.01 per line Output Delivery not tested Yes Reject > review / stop Missing or invalid input; never silently default No DEVELOPMENT / WHEN RULES OR CODE CHANGE Fixtures Known expected outputs Same calculation Shared workflow proposed Compare expected Throw on any mismatch Synthetic toy, not financial advice • fixtures do not run on customer requests

Full-size diagram

n8n is a comfortable place to put a calculation. The inputs arrive from a form or webhook, the result goes to a CRM, a sheet or an email, and the calculation sits in the middle in a Code node. The risk is that the middle step quietly becomes the part of your product that customers trust most, without the engineering habits that trust needs.

This article is about making that step deterministic: the same input and the same rule version always produce the same output, every rounding decision is written down, and an incomplete input is rejected instead of producing a confident wrong number. (Whether a calculation belongs in n8n or in custom code at all is a separate question, covered in what to automate first in a small business.)

The example in this article is a toy. It is a synthetic holding-cost estimate made up to show the engineering pattern. It is not a tax, lending or investment calculation, and nothing here is financial advice.

What "deterministic" has to cover

For a money calculation, four things have to be pinned down. If any of them is left implicit, two runs that look identical can disagree.

ConcernDecide explicitlyFailure if left implicit
Number representationHow money is held during the calculationBinary floating point turns some decimal values into near-misses, so rounding goes the wrong way
RoundingWhich rounding mode, to what precision, and at which stepTotals that don't add up, or a one-cent difference from the spreadsheet a customer used
InputsWhich fields are required, their format and allowed range, and what happens when one is missingA missing rate becomes 0 or NaN, and a plausible-looking result goes out
RulesWhich version of the parameters (fees, thresholds, formulas) produced this resultNobody can explain or reproduce last month's number after a parameter change

The rest of the article implements each of these in one n8n Code node and then tests it with fixtures.

The toy calculation

Example (synthetic): a monthly holding-cost estimate for a rented property.

  • Inputs: purchase price, deposit percentage, annual interest rate (interest-only), monthly rent, other monthly costs, currency and rule version.
  • Rule parameter: a management fee as a percentage of rent. Two made-up rule versions exist. toy-holding-cost/2026-01 uses 8.00%, and toy-holding-cost/2026-07 uses 7.50%.
  • Outputs: deposit, loan amount, monthly interest, management fee, other costs and net monthly amount.

The formulas are deliberately simple. The engineering around them is the point.

Decision 1: hold money as integer minor units

JavaScript numbers are binary floating point, and some decimal values can't be represented exactly. You can see the effect in Node.js (checked on Node 24.22.1):

js
Math.round(1.005 * 100) / 100   // 1, not 1.01
(1.005).toFixed(2)              // "1.00"
1.005 * 100                     // 100.49999999999999

Under "round half up", 1.005 should become 1.01. The float version produces 1.00, because the value stored is slightly below 1.005.

The example avoids this by:

  • accepting money and percentages as decimal strings ("2450.50", "6.25") and rejecting JSON numbers, so money values are never parsed into floats;
  • converting them to integer cents and basis points with BigInt;
  • doing every money multiplication and division in integers, with an explicit rounding function.

JavaScript numbers still exist around the calculation (the runtime, the validation code, array indexes). The guarantee is narrower and is what matters: the money arithmetic itself uses parsed BigInt minor units.

"Cents" here assumes a currency with two decimal places. The example's AUD is one. Other currencies use different minor units (some have none, some three), so a multi-currency version needs a per-currency scale rather than a hard-coded 100n.

A decimal library would also work. One practical reason for BigInt here: n8n's Code node documentation says that on n8n Cloud you can't import external npm modules (only crypto and moment are available), while self-hosted instances can enable them (n8n: Using the Code node). BigInt is part of JavaScript itself, so the same code doesn't depend on module settings.

Decision 2: name the rounding rule, and decide where it applies

The example rounds half up to 0.01, once per line item, and the net amount is the sum of the already-rounded lines. The divRoundHalfUp helper is written for non-negative values only, which every line item in this toy is. The net can be negative, but it's a subtraction of already-rounded positive lines, not a signed rounding operation. If you need to round negative intermediate values, write and test a signed rule (half away from zero vs half toward positive infinity give different answers).

That is a choice with a tradeoff:

  • Round each line, then sum (used here): the breakdown a customer sees always adds up to the total. The total can differ by a cent or two from a calculation that keeps full precision until the end.
  • Keep full precision, round only the total: the total is closer to the exact value, but the displayed line items may not add up to it, and someone will ask why.

Neither is universally right. What matters is that the rule is written down, appears in the output (the example returns a rounding field), and matches what your customers or accountants expect. If the calculation must match an external system, its rounding rule wins and should be documented.

Decision 3: reject incomplete input instead of defaulting

The most dangerous bug in a calculation workflow is a missing field that quietly becomes 0. A missing interest rate shouldn't produce a lower, more attractive cost. It should produce no number.

The example validates before calculating, collects all problems rather than stopping at the first, and returns status: "rejected" with a list of errors and the original input. The workflow then routes rejected items away from the customer-facing output.

This validation is a step you can see and test inside the Code node. n8n sub-workflows can declare the input fields and types a caller should provide (n8n: Break workflows into smaller parts). Don't treat that declaration as a replacement for checking values: format, range, currency and rule version still need explicit checks like the ones below.

Decision 4: version the rules, and record the version in every result

Fees, thresholds and formulas change. If the result doesn't record which parameters produced it, you can't reproduce or explain it later.

In the example, the input carries a rule_version. The code looks it up in a RULES table and rejects unknown versions instead of falling back to "latest". The output repeats the version.

Make the lookup strict. It's tempting to write RULES[input.rule_version] against a plain object. Don't: plain JavaScript objects inherit keys such as constructor, toString and __proto__, so RULES["constructor"] returns a function, which is truthy and passes a !rule check. An array such as ["toy-holding-cost/2026-07"] is converted to the string key and matches a real rule. An earlier version of this example used that pattern, and it let a "constructor" version with no currency reach the BigInt arithmetic and crash the node instead of returning a rejection (see How this example was tested). The version below requires a string and uses a Map, which has no inherited entries, and it reads every input field with Object.hasOwn.

Two practical consequences of versioning follow:

  • Re-running an old case with its original inputs, original version and unchanged code reproduces the original number. The parameters alone aren't enough: if the formula or code changes, the same version can give a different answer. Log a code or release identifier with each result as well, and treat a formula change as a new rule version. Re-running with the new version shows exactly what changed.
  • Changing a parameter means adding a version, not editing one. The old entry stays so historical results remain reproducible.

Who decides the default version for new requests (for example, the form always sends the current one) is a product decision. Make it explicitly.

The Code node

Mode: Run Once for Each Item (the n8n docs describe this mode as running the code for every input item; the default is "Run Once for All Items") (n8n: Using the Code node). Language: JavaScript.

Example (synthetic; tested as described in the next section):

js
// n8n Code node — mode: "Run Once for Each Item", language: JavaScript.
// SYNTHETIC toy calculation for teaching. Not tax, lending or financial advice.
// Money arithmetic uses BigInt integer minor units (cents of a two-decimal currency).

// rule_version -> parameters. A Map has no inherited keys, so names such as
// "constructor" or "__proto__" can never match a rule. Values are made up.
const RULES = new Map([
  ['toy-holding-cost/2026-01', { currency: 'AUD', mgmtFeeBp: 800n }],
  ['toy-holding-cost/2026-07', { currency: 'AUD', mgmtFeeBp: 750n }],
]);

const MONEY = /^\d{1,12}(\.\d{1,2})?$/;   // e.g. "650000" or "2450.50"
const PCT   = /^\d{1,3}(\.\d{1,2})?$/;    // e.g. "6.25" (percent, max 2 dp)

function toMinor(str) {            // "2450.5" -> 245050n (two-decimal currency)
  const [w, f = ''] = str.split('.');
  return BigInt(w) * 100n + BigInt((f + '00').slice(0, 2));
}
function toBp(str) {               // "6.25" -> 625n basis points
  const [w, f = ''] = str.split('.');
  return BigInt(w) * 100n + BigInt((f + '00').slice(0, 2));
}
function divRoundHalfUp(n, d) {    // ONLY for n >= 0, d > 0: round half up
  return (n * 2n + d) / (d * 2n);
}
function fmt(minor) {              // 245050n -> "2450.50"
  const neg = minor < 0n; const a = neg ? -minor : minor;
  return (neg ? '-' : '') + (a / 100n).toString() + '.' + (a % 100n).toString().padStart(2, '0');
}
const own = (obj, key) => (Object.hasOwn(obj, key) ? obj[key] : undefined);

const input = $input.item.json;
const errors = [];
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
  return { json: { status: 'rejected', rule_version: null, errors: [{ field: '(item)', problem: 'input must be a JSON object' }] } };
}

const version = own(input, 'rule_version');
const rule = typeof version === 'string' ? RULES.get(version) : undefined;
if (!rule) errors.push({ field: 'rule_version', problem: 'must be a string naming a known rule version' });
const currency = own(input, 'currency');
if (rule && currency !== rule.currency) {
  errors.push({ field: 'currency', problem: `expected ${rule.currency}` });
}

const moneyFields = ['purchase_price', 'monthly_rent', 'monthly_other_costs'];
const pctFields = ['deposit_pct', 'annual_interest_pct'];
for (const f of moneyFields) {
  const v = own(input, f);
  if (v === undefined || v === null || v === '') errors.push({ field: f, problem: 'missing' });
  else if (typeof v !== 'string' || !MONEY.test(v)) errors.push({ field: f, problem: 'must be a decimal string with at most 2 decimals' });
}
for (const f of pctFields) {
  const v = own(input, f);
  if (v === undefined || v === null || v === '') errors.push({ field: f, problem: 'missing' });
  else if (typeof v !== 'string' || !PCT.test(v)) errors.push({ field: f, problem: 'must be a percent string with at most 2 decimals' });
  else if (toBp(v) > 10000n) errors.push({ field: f, problem: 'must be 100 or less' });
}

if (errors.length) {
  // Do NOT substitute zero for a missing value: reject and route for review.
  return { json: { status: 'rejected', rule_version: typeof version === 'string' ? version : null, errors, input } };
}

const price = toMinor(input.purchase_price);
const deposit = divRoundHalfUp(price * toBp(input.deposit_pct), 10000n);
const loan = price - deposit;
// Simplified: interest-only, annual rate / 12, no compounding or day count.
const monthlyInterest = divRoundHalfUp(loan * toBp(input.annual_interest_pct), 120000n);
const rent = toMinor(input.monthly_rent);
const mgmtFee = divRoundHalfUp(rent * rule.mgmtFeeBp, 10000n);
const other = toMinor(input.monthly_other_costs);
// Each line item is rounded to cents first; net is the sum of rounded lines,
// so the displayed breakdown always adds up. Net may be negative.
const net = rent - mgmtFee - monthlyInterest - other;

return {
  json: {
    status: 'ok',
    rule_version: version,
    currency: rule.currency,
    rounding: 'half-up to 0.01 per line item',
    deposit: fmt(deposit),
    loan_amount: fmt(loan),
    monthly_interest: fmt(monthlyInterest),
    management_fee: fmt(mgmtFee),
    monthly_other_costs: fmt(other),
    net_monthly: fmt(net),
  },
};

How the workflow uses it

Figure (teaching diagram, to be produced): Input → validate → calculate (with a rounding note) → output, with a red "rejected" branch to review. A separate, dashed development lane shows fixtures running through the calculation into a comparison step that fails the run on any mismatch. The shared sub-workflow box is labelled proposed (not tested).

The diagram separates two things that are easy to blur together:

At runtime (every real request):

  1. Trigger (form, webhook or another workflow) supplies the input.
  2. Validate and calculate (the Code node above).
  3. An If node checks status:

- ok → continue to the customer-facing output (email, CRM field, sheet row), including rule_version and rounding; - rejected → send the item and its errors to a human review queue, or fail the execution on purpose. n8n's Stop And Error node exists for this: it can "cause executions to fail under certain conditions" and send custom error information to error workflows (n8n: Stop And Error).

During development (whenever the rules or code change):

  1. A separate test workflow feeds fixtures (known inputs) through the same calculation and compares each output with the expected value.

Fixtures are a development-time check. They don't run on every customer request, and they don't prove a production input is correct. They prove that the code still does what the fixture table says. To make sure the test exercises the same code as production, one option (proposed here, not tested for this article) is to put the Code node in a sub-workflow called by both the production workflow and the test workflow. Copying the code into two places means the test can pass while production drifts. The If, Stop And Error and delivery steps above were not tested either; only the Code node and the fixture comparison were run.

The fixture table

Each row is an input and its expected output. Inputs not shown are the same as F1. Here is F1 in full, exactly as the test workflow sends it. Note the full version keys: a shortened 2026-07 would itself be rejected.

json
{
  "rule_version": "toy-holding-cost/2026-07",
  "currency": "AUD",
  "purchase_price": "650000",
  "deposit_pct": "20",
  "annual_interest_pct": "6.25",
  "monthly_rent": "2600",
  "monthly_other_costs": "410.00"
}
FixtureWhat it testsInput differences from F1Expected statusExpected key outputs
F1Baseline with current rulesnoneokinterest 2708.33 · fee 195.00 · net −713.33
F2Same input, older rule versionrule_version toy-holding-cost/2026-01okinterest 2708.33 · fee 208.00 · net −726.33
F3Exact half-cent roundingprice 100000, deposit 10%, rate 6.01%, rent 1000.60, other 0okinterest 450.75 · fee 75.05 (7.5% of 1000.60 = 75.045 → half up) · net 474.80
F4Missing inputannual_interest_pct absentrejectedannual_interest_pct: missing
F5Wrong type and currencyprice sent as the JSON number 650000.1, currency USDrejectedcurrency and purchase_price
F6Unknown rule versiontoy-holding-cost/2027-01rejectedrule_version
F7–F9Inherited object keys as the versionconstructor, toString, __proto__, with currency absentrejectedrule_version (not a crash)
F10Inherited key, currency presenthasOwnProperty, currency AUDrejectedrule_version (not a misleading currency error)
F11–F13Non-string or missing versionnull, the number 202607, absentrejectedrule_version
F14Valid version, currency missingcurrency absentrejectedcurrency
F15Version wrapped in an array["toy-holding-cost/2026-07"]rejectedrule_version (not silently accepted)

F3 is the one to keep even if you trim the others. It sits exactly on a rounding boundary. Under round-half-even ("banker's rounding") the fee would be 75.04 instead of 75.05, so this fixture fails loudly if someone changes the rounding mode without meaning to.

F5 deliberately sends a number instead of a string. Rejecting it is a choice: it forces every caller to send money as text, so money never enters the calculation as a float. If your callers can't do that, convert at the boundary with a documented rule and add a fixture for it.

F7–F15 exist because an earlier version of this example had exactly this bug (described under Decision 4). Keep negative fixtures like these for any lookup keyed by user-supplied text.

The comparison step checks every field of each output (status, version, currency, rounding label, all six money fields, and each error's field and message), excluding only the echoed input. If any fixture differs, it throws, so the test execution itself fails rather than just reporting a false flag.

How this example was tested

  • Environment: self-hosted n8n 2.46.6, run locally from the command line (n8n execute) on Node.js 24.22.1. Code node at default settings, "Run Once for Each Item".
  • Before the fix: the earlier version of the code, fed the new fixtures, failed the execution with Cannot mix BigInt and other types on F7 ("constructor"). Run outside n8n with the same code, F7–F9 crashed, F10 was rejected for the wrong reason and F15 was accepted and calculated.
  • After the fix: a test workflow (Manual Trigger → Fixtures → the Code node above → a comparison Code node) ran all 15 fixtures. All 15 matched every asserted field, and the execution succeeded.
  • Negative control: the same check with one expectation deliberately changed (F3 fee 75.04) failed the execution with Fixture check failed: F3, showing the comparison step actually fails the run on a mismatch.
  • Not tested: n8n Cloud, other n8n versions, the Python Code node, the sub-workflow arrangement, the If and Stop And Error routing, delivery, or any real data source. Fifteen passing fixtures show the code does what the table says. They don't prove every possible bad input is rejected.

If you adapt the code, re-run the fixtures on the n8n version and hosting type you deploy to before trusting it. n8n's own documentation notes that the Code node's runtime and available modules differ between versions and between Cloud and self-hosted.

Edge cases worth adding fixtures for

  • Negative results. The net can be negative, as in F1. Make sure the output format and anything downstream (emails, charts) handle the minus sign.
  • Interest model. The toy uses interest-only, annual rate ÷ 12, with no compounding or day count. Real lending calculations differ, so state your model and test it.
  • Very large values. The input pattern limits money to 12 integer digits. Decide your real bounds and test them.
  • Zero values that are legitimate, such as zero other costs in F3, versus missing values, as in F4. Your validation must tell them apart, which is why the check is "missing" and not "falsy".
  • Whitespace and locale formats like "2,450.50" or "2450,50". The example rejects them. If you accept them, normalise them at the boundary and add fixtures.
  • Rule changes mid-request. If a long-running workflow reads the current version at the start, it should keep using it to the end.

Where this pattern comes from

The PropSight case study describes a property-investor product whose n8n workflows run financial models (out-of-pocket, tax and break-even). That's the kind of system this article addresses. The case file is an author-written description; its model configurations weren't inspected for this article, and nothing above describes them. The calculation, rule versions and numbers here are synthetic.

Checklist

  • Money and rates arrive as strings, and money arithmetic uses integer minor units for the currency's real scale (or a decimal type), not floats.
  • The rounding mode, precision and step are written down and returned with the result.
  • Missing, malformed and out-of-range inputs are rejected with all errors listed. Nothing defaults to zero.
  • Every result carries the rule version (and a code/release identifier) that produced it. Unknown, non-string and inherited-key versions are rejected.
  • Rejected items go to review or fail visibly, never to the customer-facing output.
  • A fixture table covers a baseline, each rule version, a rounding boundary and each rejection type.
  • Fixtures run against the same code production runs, on the n8n version and hosting type you deploy to, and a mismatch fails the test run.

Need a calculation workflow you can explain?

If your product depends on calculations running in n8n and you want them versioned, tested and explainable, see AI systems and automation.


Sources

Put the thinking to work

What could this change for you?

Tell me what you’re building — I’ll tell you honestly where I’d start.

Start a project with me