Simple Math
The goal of this example function is to calculate the total amount by simply adding a subtotal and tax within the construct of an advanced event code. The type of function can be particularly useful in scenarios where you need to ensure accurate calculations of financial transactions, such as generating totals from order line items or similar.
function E_MATH_SAMPLE_1234() {
var subtotal = $P["P_SUBTOTAL_1234"].firstValue();
var tax = $P["P_TAX_5678"].firstValue();
subtotal = parseFloat(subtotal);
tax = parseFloat(tax);
// Confirm that both variables are numbers
if (isNaN(subtotal) || isNaN(tax)) {
return;
}
var total = subtotal + tax;
if (total >= 500) {
$F.setFacts("E_MATH_SAMPLE_1234");
}
}
Function details
-
Retrieving Values: The function starts by retrieving the values of
subtotalandtaxfrom predefined parameters (P_SUBTOTAL_1234andP_TAX_5678). These values are expected to be strings. -
Parsing Values: It then converts these string values to floating-point numbers using
parseFloat. This step is crucial to ensure that mathematical operations can be performed on these values. -
Validation: The function checks if either
subtotalortaxisNaN(Not-a-Number). If either value isNaN, the function exits early (return), ensuring that invalid inputs do not proceed to the calculation step. -
Calculating Total: If both values are valid numbers, the function calculates the total by adding
subtotalandtax. -
Setting Facts: Finally, if the total amount is greater than or equal to 500, the function sets a fact (
E_MATH_SAMPLE_1234).
By using this or similar functions in advanced events, event creators can ensure that any financial calculations are accurate and automated, reducing the risk of reporting errors.