Skip to main content

Utility Functions

Mathematical and utility helper functions for everyday operations.

For the internal C# utility that assigns unique references to loan quotes, see Loan Request ID Generation. It is used by the loan-origination commands and is not available to JavaScript scripts.

The execution engine also provides numberToWords() as a global JavaScript helper for converting amounts and other non-negative numbers into English words.

round()

Round a decimal number to a specified number of decimal places.

Syntax

round(value, decimals)

Parameters

ParameterTypeRequiredDescription
valuenumberYesThe number to round
decimalsnumberYesNumber of decimal places (0 or more)

Returns

Returns a decimal number rounded to the specified number of decimal places.

Rounding method

The standard command-formula helper follows JavaScript Math.round semantics with decimal-place shifting. The list-expression runtime uses .NET MidpointRounding.AwayFromZero. Avoid depending on negative midpoint behavior when moving a formula between those runtimes.

Examples

Currency Rounding

var rawAmount = 1234.56789;
var rounded = round(rawAmount, 2);

console.log(rounded); // Output: 1234.57

return {
originalAmount: rawAmount,
displayAmount: rounded
};

Interest Calculation

var principal = 50000;
var interestRate = 12.5; // 12.5%
var days = 30;

var rawInterest = (principal * interestRate * days) / (365 * 100);
var interest = round(rawInterest, 2);

console.log('Interest: ' + interest);
// Output: Interest: 513.70

return {
principal: principal,
interestRate: interestRate,
days: days,
interest: interest,
total: round(principal + interest, 2)
};

Percentage Calculations

var amount = 15678.45;
var percentage = 3.75;

var calculatedAmount = (amount * percentage) / 100;
var roundedAmount = round(calculatedAmount, 2);

return {
baseAmount: amount,
percentage: percentage,
calculatedAmount: roundedAmount
};

Remove Decimal Places

var value = 123.456789;

var rounded0 = round(value, 0); // 123
var rounded2 = round(value, 2); // 123.46
var rounded4 = round(value, 4); // 123.4568

return {
original: value,
noDecimals: rounded0,
twoDecimals: rounded2,
fourDecimals: rounded4
};

Loan EMI Calculation

function calculateEMI(principal, annualRate, months) {
var monthlyRate = annualRate / (12 * 100);
var numerator = principal * monthlyRate * Math.pow(1 + monthlyRate, months);
var denominator = Math.pow(1 + monthlyRate, months) - 1;
var emi = numerator / denominator;

return round(emi, 2);
}

var loanAmount = 100000;
var annualInterestRate = 10.5;
var tenureMonths = 24;

var emi = calculateEMI(loanAmount, annualInterestRate, tenureMonths);

return {
loanAmount: loanAmount,
interestRate: annualInterestRate,
tenure: tenureMonths,
monthlyEMI: emi,
totalPayment: round(emi * tenureMonths, 2),
totalInterest: round((emi * tenureMonths) - loanAmount, 2)
};

Multiple Calculations

var deposit = 25000;
var withdrawals = [5000.123, 3500.456, 1200.789];

var totalWithdrawals = withdrawals.reduce(function(sum, amount) {
return sum + amount;
}, 0);

var roundedWithdrawals = round(totalWithdrawals, 2);
var balance = round(deposit - roundedWithdrawals, 2);

return {
initialDeposit: deposit,
totalWithdrawals: roundedWithdrawals,
currentBalance: balance
};

Common Use Cases

  1. Currency Display: Always round to 2 decimal places
  2. Interest Calculations: Round to 2 decimal places for money
  3. Percentage Display: Round to 2-4 decimal places
  4. Statistics: Round to appropriate precision
  5. Avoid Floating-Point Errors: Round after arithmetic operations

Floating-Point Precision Issues

JavaScript uses IEEE 754 floating-point arithmetic, which can produce unexpected results:

// Problem: Floating-point precision
var result = 0.1 + 0.2;
console.log(result); // 0.30000000000000004

// Solution: Use round()
var correct = round(0.1 + 0.2, 2);
console.log(correct); // 0.30

Best Practices

✅ Do

  1. Always round currency values

    var total = round(subtotal + tax, 2);
  2. Round after calculations

    var result = round((amount * rate) / 100, 2);
  3. Store raw values, display rounded

    var rawValue = 123.456789;
    return {
    value: rawValue, // Store precise
    display: round(rawValue, 2) // Show rounded
    };
  4. Round final results

    var sum = values.reduce((a, b) => a + b, 0);
    var average = round(sum / values.length, 2);

❌ Don't

  1. Don't round intermediate calculations

    // Bad: Compounds rounding errors
    var step1 = round(amount * 0.1, 2);
    var step2 = round(step1 * 1.15, 2);

    // Good: Round only at the end
    var result = round(amount * 0.1 * 1.15, 2);
  2. Don't compare rounded and unrounded values

    // Bad
    if (round(value, 2) === value) { }

    // Good
    if (round(value, 2) === round(expected, 2)) { }
  3. Don't forget to round user inputs

    var userAmount = context.amount;
    var validated = round(userAmount, 2); // Ensure 2 decimals

console.log() / console.warn() / console.error()

Log messages for debugging (limited functionality in production).

Syntax

console.log(message)
console.warn(message)
console.error(message)

Parameters

ParameterTypeRequiredDescription
messageanyYesMessage or object to log

Returns

No return value (void).

Examples

Basic Logging

console.log('Processing transaction');
var result = doCmd('ProcessTransaction', context);
console.log('Transaction completed: ' + result.transactionId);

return result;

Error Logging

try {
var result = doCmd('CriticalOperation', context);
return result;
} catch (error) {
console.error('Operation failed: ' + error.message);
throw error;
}

Debug Information

console.log('Input parameters:', context);

var account = doCmd('GetAccount', {
accountNumber: context.accountNumber
});

console.log('Account balance:', account.balance);

return account;

Notes

  • Standard command execution returns these entries in the response logs collection
  • Some specialized execution modes replace logging with no-op functions
  • Use logging for diagnostics, never for business logic
  • Do not log secrets, tokens, credentials, or unnecessary customer data
  • Pass one string or object per call

Common Utility Patterns

Pattern 1: Safe Division with Rounding

function safeDivide(numerator, denominator, decimals) {
if (denominator === 0) {
return 0;
}
return round(numerator / denominator, decimals);
}

var average = safeDivide(totalAmount, itemCount, 2);

Pattern 2: Percentage Calculation

function calculatePercentage(part, whole, decimals) {
if (whole === 0) {
return 0;
}
return round((part / whole) * 100, decimals || 2);
}

var completionRate = calculatePercentage(completed, total, 2);
// Returns: 75.50 for 75.5%

Pattern 3: Currency Formatting Helper

function formatCurrency(amount, currencySymbol) {
var rounded = round(amount, 2);
var parts = rounded.toFixed(2).split('.');
var integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return (currencySymbol || '$') + integerPart + '.' + parts[1];
}

var display = formatCurrency(1234567.89, '₦');
// Returns: ₦1,234,567.89

Pattern 4: Calculate Compound Interest

function calculateCompoundInterest(principal, rate, years, decimals) {
var amount = principal * Math.pow(1 + (rate / 100), years);
return round(amount, decimals || 2);
}

var futureValue = calculateCompoundInterest(10000, 8.5, 5, 2);
console.log('Future value: ' + futureValue);

Pattern 5: Prorated Calculation

function calculateProrated(fullAmount, totalDays, actualDays, decimals) {
if (totalDays === 0) {
return 0;
}
var dailyRate = fullAmount / totalDays;
var proratedAmount = dailyRate * actualDays;
return round(proratedAmount, decimals || 2);
}

var proratedFee = calculateProrated(1000, 30, 15, 2);
// Returns: 500.00 for half month

Complete Example: Loan Calculation

// Loan calculation with proper rounding
function calculateLoanDetails(loanAmount, annualRate, months) {
console.log('Calculating loan for amount: ' + loanAmount);

// Calculate monthly interest rate
var monthlyRate = annualRate / (12 * 100);

// Calculate EMI using formula
var emi;
if (monthlyRate === 0) {
emi = loanAmount / months;
} else {
var numerator = loanAmount * monthlyRate * Math.pow(1 + monthlyRate, months);
var denominator = Math.pow(1 + monthlyRate, months) - 1;
emi = numerator / denominator;
}

// Round EMI to 2 decimal places
emi = round(emi, 2);

// Calculate totals
var totalPayment = round(emi * months, 2);
var totalInterest = round(totalPayment - loanAmount, 2);
var effectiveRate = round((totalInterest / loanAmount) * 100, 2);

console.log('EMI calculated: ' + emi);

// Generate schedule
var balance = loanAmount;
var schedules = [];

for (var i = 1; i <= months; i++) {
var interestComponent = round(balance * monthlyRate, 2);
var principalComponent = round(emi - interestComponent, 2);
balance = round(balance - principalComponent, 2);

// Adjust last payment for rounding differences
if (i === months && balance !== 0) {
principalComponent = round(principalComponent + balance, 2);
balance = 0;
}

schedules.push({
installment: i,
emi: emi,
principal: principalComponent,
interest: interestComponent,
balance: balance
});
}

return {
loanAmount: loanAmount,
interestRate: annualRate,
tenure: months,
monthlyEMI: emi,
totalPayment: totalPayment,
totalInterest: totalInterest,
effectiveRate: effectiveRate,
schedules: schedules
};
}

// Usage
var loanDetails = calculateLoanDetails(100000, 12, 24);

console.log('Total interest: ' + loanDetails.totalInterest);

return loanDetails;

Tips & Tricks

1. Handling Nulls and Undefined

function safeRound(value, decimals) {
if (value === null || value === undefined || isNaN(value)) {
return 0;
}
return round(value, decimals);
}

2. Rounding Arrays

function roundArray(arr, decimals) {
return arr.map(function(value) {
return round(value, decimals);
});
}

var amounts = [123.456, 789.012, 345.678];
var rounded = roundArray(amounts, 2);
// Returns: [123.46, 789.01, 345.68]

3. Sum with Rounding

function sumAndRound(values, decimals) {
var sum = values.reduce(function(acc, val) {
return acc + val;
}, 0);
return round(sum, decimals);
}

var total = sumAndRound([12.345, 67.890, 23.456], 2);

4. Conditional Rounding

function smartRound(value, isCurrency) {
return isCurrency ? round(value, 2) : round(value, 4);
}

var price = smartRound(12.34567, true); // 12.35
var rate = smartRound(0.123456, false); // 0.1235

Mathematical Operations

Safe Arithmetic with Rounding

// Addition
var sum = round(value1 + value2, 2);

// Subtraction
var difference = round(value1 - value2, 2);

// Multiplication
var product = round(value1 * value2, 2);

// Division
var quotient = value2 !== 0 ? round(value1 / value2, 2) : 0;

// Percentage
var percentage = round((part / whole) * 100, 2);

// Power
var power = round(Math.pow(base, exponent), 2);

// Square root
var sqrt = round(Math.sqrt(value), 2);

See Also