UNPKG

@kikiutils/node

Version:

A modular utility library for Node.js offering secure hashing, flexible logging, datetime manipulation, and more.

38 lines (34 loc) 1.5 kB
'use strict'; const decimal_js = require('decimal.js'); /** * Converts a fraction (numerator / denominator) into a percentage string. * * - Uses `decimal.js` for precise decimal calculations. * - Supports custom decimal places and optional percentage symbol. * - Returns `'0.00%'` if result is `NaN` or division is invalid. * * @param {CalculableValue} molecular - The numerator of the fraction. * @param {CalculableValue} denominator - The denominator of the fraction. * @param {ToPercentageStringOptions} [options] - Optional output settings. * @returns {string} Formatted percentage string. * * @example * ```typescript * import { toPercentageString } from '@kikiutils/node/math'; * * console.log(toPercentageString(50, 200)); // 25.00% * console.log(toPercentageString(50, 200, { withSymbol: false })); // 25.00 * console.log(toPercentageString(50, 200, { decimalPlaces: 1 })); // 25.0% * ``` */ function toPercentageString(molecular, denominator, options) { const molecularDecimal = new decimal_js.Decimal(molecular.toString()); const denominatorDecimal = new decimal_js.Decimal(denominator.toString()); const calculationResult = molecularDecimal.div(denominatorDecimal); const result = calculationResult.isNaN() ? '0.00' : calculationResult.times(100).toFixed(options?.decimalPlaces ?? 2); return options?.withSymbol ?? true ? `${result}%` : result; } exports.toPercentageString = toPercentageString; //# sourceMappingURL=math.cjs.map