Mathematics Functions¶
Mathematical operations and arithmetic functions.
$Max¶
Returns the larger of two numbers.
Signature¶
Parameters¶
a(decimal): First numberb(decimal): Second number
Returns¶
- (decimal): The larger value
Examples¶
max = $Max(10, 20); // 20
max = $Max(-5, -10); // -5
max = $Max(3.5, 3.4); // 3.5
// With variables
price1 = 1200;
price2 = 1500;
higher = $Max(price1, price2); // 1500
// In calculations
premium = $Max(basePremium, minPremium);
Notes¶
- Both parameters must be numbers
- Cannot be called with arrays or other types
$Min¶
Returns the smaller of two numbers.
Signature¶
Parameters¶
a(decimal): First numberb(decimal): Second number
Returns¶
- (decimal): The smaller value
Examples¶
min = $Min(10, 20); // 10
min = $Min(-5, -10); // -10
min = $Min(3.5, 3.4); // 3.4
// Clamping maximum
premium = $Min(calculatedPremium, maxPremium);
// Finding lower bound
cost = $Min(estimate1, estimate2);
Notes¶
- Both parameters must be numbers
- Use with
$Maxfor clamping values
$Abs¶
Returns the absolute value of a number.
Signature¶
Parameters¶
value(decimal): The number
Returns¶
- (decimal): The absolute value (always positive or zero)
Examples¶
abs1 = $Abs(-15); // 15
abs2 = $Abs(15); // 15
abs3 = $Abs(0); // 0
// Distance calculation
difference = $Abs(value1 - value2);
// Magnitude
magnitude = $Abs(adjustment);
// Check threshold
if ($Abs(delta) > threshold) {
// Significant change
}
Notes¶
- Always returns a non-negative number
- Useful for calculating distances and differences
$Round¶
Rounds a number to a specified number of decimal places.
Signature¶
Parameters¶
value(decimal): The number to rounddecimals(decimal): Number of decimal places (0 or positive integer)
Returns¶
- (decimal): The rounded value
Examples¶
rounded = $Round(3.14159, 2); // 3.14
rounded = $Round(3.14159, 0); // 3
rounded = $Round(1.5, 0); // 2 (rounds to even)
rounded = $Round(2.5, 0); // 2 (rounds to even)
// Financial calculations
premium = $Round(basePremium * factor, 2);
// Display formatting
displayValue = $Round(calculatedValue, 2);
// Percentage calculations
percentage = $Round((part / total) * 100, 1);
Notes¶
- Uses "banker's rounding" (rounds to nearest even number when exactly halfway)
- Commonly used with 2 decimal places for currency
- Second parameter must be non-negative integer
$Sum¶
Calculates the sum of all values in an array.
Signature¶
// Simple array of numbers
$Sum(array);
// Array of objects with property
$Sum(array, propertyName);
Parameters¶
array(InstanceArray): Array of numbers or objectspropertyName(string, optional): Property name to sum (for arrays of objects)
Returns¶
- (decimal): The sum of all values
Examples¶
Simple array:
numbers = [1, 2, 3, 4, 5];
total = $Sum(numbers); // 15
prices = [10.5, 20.25, 15.75];
totalPrice = $Sum(prices); // 46.50
Array of objects:
orders = [
{ id: 1, amount: 100 },
{ id: 2, amount: 150 },
{ id: 3, amount: 200 },
];
totalAmount = $Sum(orders, "amount"); // 450
policies = [
{ number: "P1", premium: 1200 },
{ number: "P2", premium: 1500 },
{ number: "P3", premium: 1100 },
];
totalPremiums = $Sum(policies, "premium"); // 3800
Empty array:
Common Patterns¶
Calculate total:
Sum filtered values:
Nested property:
// For nested properties, map first
departments = getDepartments();
allSalaries = departments
.Map((d) => $Sum(d.employees, "salary"))
.ReduceToNum((acc, x) => acc + x, 0);
Notes¶
- Returns 0 for empty arrays
- All values must be numbers
- For objects, property must exist and be numeric
- Alternative: Use
.ReduceToNum()for more complex aggregations
Common Patterns¶
Pattern 1: Clamp Value¶
// Ensure value is within range
function clamp(value, min, max) {
return $Max(min, $Min(value, max));
}
clamped = clamp(150, 100, 200); // 150
clamped = clamp(50, 100, 200); // 100
clamped = clamp(250, 100, 200); // 200
Pattern 2: Average Calculation¶
numbers = [10, 20, 30, 40, 50];
sum = $Sum(numbers);
average = $Round(sum / numbers.Length, 2); // 30
Pattern 3: Distance Between Values¶
distance = $Abs(value1 - value2);
// Check if values are close
tolerance = 0.01;
areClose = $Abs(actual - expected) < tolerance;
Pattern 4: Percentage Calculations¶
total = $Sum(values);
percentages = values.Map((v) => $Round((v / total) * 100, 1));
// Ensure values are within percentage range
percentage = $Max(0, $Min(calculatedPercentage, 100));
Pattern 5: Financial Rounding¶
// Always round currency to 2 decimals
function calculatePremium(coverage, rate) {
raw = coverage * rate;
return $Round(raw, 2);
}
premium = calculatePremium(250000, 0.0048);
Pattern 6: Range Validation¶
function isInRange(value, min, max) {
return value >= min && value <= max;
}
// Or using min/max
function normalizeToRange(value, min, max) {
normalized = $Max(min, $Min(value, max));
return normalized;
}
Comparison with Manual Calculations¶
Using Functions¶
Manual Equivalent¶
// More verbose
max = a > b ? a : b;
sum = 0;
i = 0;
while (i < numbers.Length) {
sum += numbers[i];
i++;
}
// No direct equivalent for Round
Performance Notes¶
$Sumis optimized for array summation$Maxand$Minare direct C# Math calls$Rounduses banker's rounding (IEEE standard)- For single comparisons, use operators (
>,<, etc.) - For array operations, prefer native functions
Related Functions¶
Mathematical Operations¶
Array Aggregation¶
- $Sum - Sum array values
- .ReduceToNum() - Custom numeric reduction
- .Length - Array size
Comparisons¶
- $Max, $Min - Compare two values
- Comparison Operators -
>,<,>=,<=,==,!=
Best Practices¶
1. Always Round Currency¶
// Good
premium = $Round(coverage * rate, 2);
// Risky: Floating point precision issues
premium = coverage * rate;
2. Use Clamp Pattern¶
// Good: Value guaranteed in range
premium = $Max(minPremium, $Min(calculated, maxPremium));
// Less clear
if (calculated < minPremium) {
premium = minPremium;
} else if (calculated > maxPremium) {
premium = maxPremium;
} else {
premium = calculated;
}
3. Prefer $Sum for Arrays¶
4. Name Magic Numbers¶
// Good
CURRENCY_DECIMALS = 2;
premium = $Round(calculated, CURRENCY_DECIMALS);
// Less clear
premium = $Round(calculated, 2);
Advanced Examples¶
Example 1: Premium Calculation¶
function calculatePremium(coverage, age, risk) {
BASE_RATE = 0.001;
// Base calculation
base = coverage * BASE_RATE;
// Age adjustment
ageFactor = age < 25 ? 1.5 : age > 65 ? 1.25 : 1.0;
// Risk adjustment
riskFactor = risk == "high" ? 1.3 : risk == "low" ? 0.9 : 1.0;
// Calculate
calculated = base * ageFactor * riskFactor;
// Apply bounds
MIN_PREMIUM = 500;
MAX_PREMIUM = 10000;
bounded = $Max(MIN_PREMIUM, $Min(calculated, MAX_PREMIUM));
// Round to currency
return $Round(bounded, 2);
}
premium = calculatePremium(250000, 30, "standard");
Example 2: Statistical Analysis¶
function analyzeData(values) {
count = values.Length;
total = $Sum(values);
average = total / count;
// Find range
min = values.ReduceToNum((acc, x) => $Min(acc, x), values[0]);
max = values.ReduceToNum((acc, x) => $Max(acc, x), values[0]);
range = max - min;
// Calculate variance
squaredDiffs = values.Map((x) => {
diff = x - average;
return diff * diff;
});
variance = $Sum(squaredDiffs) / count;
return {
count: count,
sum: $Round(total, 2),
average: $Round(average, 2),
min: min,
max: max,
range: $Round(range, 2),
variance: $Round(variance, 2),
};
}
data = [10, 15, 20, 25, 30, 35, 40];
stats = analyzeData(data);
Example 3: Batch Processing¶
function processBatch(orders) {
// Calculate totals
subtotal = $Sum(orders, "amount");
taxAmount = $Round(subtotal * 0.08, 2);
total = subtotal + taxAmount;
// Find extremes
minOrder = orders.ReduceToNum(
(acc, o) => $Min(acc, o.amount),
orders[0].amount
);
maxOrder = orders.ReduceToNum(
(acc, o) => $Max(acc, o.amount),
orders[0].amount
);
// Calculate average
avgOrder = $Round(subtotal / orders.Length, 2);
return {
orderCount: orders.Length,
subtotal: $Round(subtotal, 2),
tax: taxAmount,
total: $Round(total, 2),
minOrder: minOrder,
maxOrder: maxOrder,
avgOrder: avgOrder,
};
}
Next Steps¶
-
Explore other categories:
- Array Functions
-
Learn related concepts:
-
See practical examples:
- Basic Calculations
- Business Rules