
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.
- Define the field to sum (
price). - Choose the operation (
Sum,Average,Min,Max). - 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()orparseInt(). {{ 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
- Write an expression that takes
price = 10andqty = 3and calculates a total with 10% discount. - Use the Aggregate node to find the highest number in a list:
[10, 50, 5, 100]. - How do you round a number to exactly 2 decimal places? (Research:
toFixed(2)). - Why does
0.1 + 0.2not equal0.3in Javascript? (How do you solve this in n8n?) - 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).