Overview
The math tools module provides precision-safe mathematical operations designed for financial calculations, avoiding floating-point arithmetic errors common in JavaScript. Source:src/tools/mathTools.ts
addition
Performs precision-safe addition on an array of numbers by scaling to integers, preventing floating-point arithmetic errors.Parameters
Array of numbers to sum
Number of decimal places for precision. Values are scaled by 10^digits before addition.
Returns
Scaled integer sum as a string. The result is multiplied by 10^digits to maintain precision.
Examples
This function returns a scaled integer as a string to avoid floating-point precision errors. Divide the result by 10^digits to get the actual decimal value.
fixDecimals
Formats a number to a fixed number of decimal places with proper rounding and padding.Parameters
The number to format. Can be a number or numeric string.
Number of decimal places to format to
Returns
Formatted number as a string with exactly the specified number of decimal places. Returns “0.00” for invalid input.
Examples
This function properly handles decimal padding (e.g., 12.3 becomes “12.30”) and returns a safe default of “0.00” for invalid inputs, making it ideal for financial data formatting in UBL documents.
Use Cases
- Formatting monetary amounts in UBL invoices
- Ensuring consistent decimal precision across document fields
- Handling user input that may be strings or numbers
- Preventing floating-point display issues in tax calculations