separate.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.separate = separate;
/**
 * Inserts a separator character into a number for improved readability.
 *
 * This function groups digits in the integer part of a number into segments
 * (such as thousands) and optionally preserves decimal parts. Useful for
 * formatting large numbers like `1000000` into `1,000,000`.
 *
 * @param {number} n - The number to format.
 * @param {Object} [options] - Optional formatting settings.
 * @param {string} [options.char=","] - The character used to separate digit groups.
 * @param {number} [options.segment=3] - The number of digits per group.
 * @returns {string} The formatted number string with separators applied.
 *
 * @example
 * separate(1234567)
 * // Returns: "1,234,567"
 *
 * @example
 * separate(1234567.89)
 * // Returns: "1,234,567.89"
 *
 * @example
 * separate(987654321, { char: " ", segment: 3 })
 * // Returns: "987 654 321"
 *
 * @example
 * separate(123456, { segment: 2, char: "_" })
 * // Returns: "1_23_45_6"
 */
function separate(n, { char = ",", segment = 3 } = {}) {
    const parts = n.toString().split(".");
    const regex = new RegExp(`\\B(?=(\\d{${segment}})+(?!\\d))`, "g");
    parts[0] = parts[0].replace(regex, char);
    return parts.join(".");
}