Module 4 Lesson 3: Math in n8n
·Automation

Module 4 Lesson 3: Math in n8n

Numbers don't lie. Learn how to perform calculations, handle currencies, and use the 'Aggregate' nodes to sum up values across multiple items.

Module 4 Lesson 3: Math in n8n

From calculating sales tax to finding the average temperature across 10 sensors, math is everywhere in automation.

1. Simple Arithmetic

You can do math directly in any expression:

  • Addition: {{ $json.price + $json.tax }}
  • Percentage: {{ $json.total * 0.2 }} (20% Tip).
  • Rounding: {{ Math.round($json.total) }}

2. The Aggregate Node (The Sum/Average)

If a node outputs 10 items (e.g., 10 separate orders), and you want to know the Total Sum, you use the Aggregate node.

  1. Define the field to sum (price).
  2. Choose the operation (Sum, Average, Min, Max).
  3. The node will output ONE single item containing the final result.

3. Dealing with "Strings that look like Numbers"

If an API returns "100" as a string, 100 + 20 might equal "10020" (concatenation) instead of 120.

  • The Fix: Use Number() or parseInt().
  • {{ Number($json.price) + 20 }}

4. Currency Math (Decimal Safety)

Never use floating-point math for money if you can avoid it.

  • Tip: Convert everything to Cents (Integers), do your math, and then convert back to Dollars at the final step.
  • (1099 * 1.05) / 100 ($10.99 + 5% tax).

Exercise: The Accountant's Lab

  1. Write an expression that takes price = 10 and qty = 3 and calculates a total with 10% discount.
  2. Use the Aggregate node to find the highest number in a list: [10, 50, 5, 100].
  3. How do you round a number to exactly 2 decimal places? (Research: toFixed(2)).
  4. Why does 0.1 + 0.2 not equal 0.3 in Javascript? (How do you solve this in n8n?)
  5. Research: What is the "Item Lists" node and how does it help with math?

Summary

Math nodes turn n8n into a "Spreadsheet on Autopilot." By mastering calculations and aggregates, you can build complex reporting and billing systems that are accurate, automated, and error-free.

Next Lesson: Keeping time: Dealing with Dates (Luxon and native Date).

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn