Skip to main content

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.
function addition(items: number[], digits?: number): string

Parameters

items
number[]
required
Array of numbers to sum
digits
number
default:2
Number of decimal places for precision. Values are scaled by 10^digits before addition.

Returns

result
string
Scaled integer sum as a string. The result is multiplied by 10^digits to maintain precision.

Examples

import { addition } from 'ubl-builder';

// Standard 2-digit precision (default)
const sum = addition([1.2, 2.3]);
console.log(sum); // "350" (represents 3.50 scaled by 100)

// Divide by 10^digits to get actual value
const actualValue = parseFloat(sum) / 100;
console.log(actualValue); // 3.5
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.
function fixDecimals(value: number | string, decimals?: number): string

Parameters

value
number | string
required
The number to format. Can be a number or numeric string.
decimals
number
default:2
Number of decimal places to format to

Returns

formatted
string
Formatted number as a string with exactly the specified number of decimal places. Returns “0.00” for invalid input.

Examples

import { fixDecimals } from 'ubl-builder';

const formatted = fixDecimals(123.45);
console.log(formatted); // "123.45"

const rounded = fixDecimals(123.456);
console.log(rounded); // "123.45"
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

Build docs developers (and LLMs) love