UNPKG

@nexim/financial-calculate

Version:

Provides a set of utils to handle common financial operations.

79 lines 2.64 kB
const safeRound = (number, decimalPlaces = 2) => { if (isNaN(number) || !isFinite(number)) return 0; const factor = Math.pow(10, decimalPlaces); return Math.round((number + Number.EPSILON) * factor) / factor; }; /** * Calculate the price after applying a discount. * * @param price - The original price. * @param discount - The discount percentage to apply. * @param decimal - The number of decimal places to round to (default is 2). * * @example * ```ts * calculateDiscountedPrice(100, 10, 1); // returns 90.0 * ``` */ export function calculateDiscountedPrice(price, discount, decimal = 2) { if (price <= 0 || discount < 0) return 0; const discountedPrice = price * (1 - discount / 100); return safeRound(discountedPrice, decimal); } /** * Calculate the discount amount from the original price. * * @param price - The original price. * @param discount - The discount percentage. * @param decimal - The number of decimal places to round to (default is 2). * * @example * ```ts * calculateDiscountAmount(100, 10, 1); // returns 10.0 * ``` */ export function calculateDiscountAmount(price, discount, decimal = 2) { if (price <= 0 || discount < 0) return 0; const discountAmount = (price * discount) / 100; return safeRound(discountAmount, decimal); } /** * Calculates the profit percentage between the selling price and the cost price. * * @param sellingPrice - The selling price of the item. * @param costPrice - The cost price of the item. * @param decimal - The number of decimal places to round the result to (default is 2). * * @example * ```ts * calculatePercentageProfit(100, 80); // Returns 25.00 * ``` */ export function calculatePercentageProfit(sellingPrice, costPrice, decimal = 2) { if (costPrice <= 0 || sellingPrice < 0) return 0; const percentage = ((sellingPrice - costPrice) / costPrice) * 100; return safeRound(percentage, decimal); } /** * Calculates the discount percentage between the market price and the sale price. * * @param marketPrice - The original market price of the item. * @param salePrice - The sale price of the item. * @param decimal - The number of decimal places to round the result to (default is 2). * * @example * ```ts * calculatePercentageDiscount(100, 80); // Returns 20.00 * ``` */ export function calculatePercentageDiscount(marketPrice, salePrice, decimal = 2) { if (marketPrice <= 0 || salePrice < 0) return 0; const percentage = ((marketPrice - salePrice) / marketPrice) * 100; return safeRound(percentage, decimal); } //# sourceMappingURL=main.js.map