Skip to content

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.

Example
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

  1. Retrieving Values: The function starts by retrieving the values of subtotal and tax from predefined parameters (P_SUBTOTAL_1234 and P_TAX_5678). These values are expected to be strings.

  2. 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.

  3. Validation: The function checks if either subtotal or tax is NaN (Not-a-Number). If either value is NaN, the function exits early (return), ensuring that invalid inputs do not proceed to the calculation step.

  4. Calculating Total: If both values are valid numbers, the function calculates the total by adding subtotal and tax.

  5. 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.