-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath.ts
53 lines (49 loc) · 1.98 KB
/
math.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import Decimal from 'decimal.js';
type CalculableValue = Decimal.Value | { toString: () => string };
/**
* Options for configuring the output of the `calculateToPercentageString` function.
*/
export interface CalculateToPercentageStringOptions {
/**
* The number of decimal places to include in the result.
* @default 2
*/
decimalPlaces?: number;
/**
* Whether to include the '%' symbol in the result.
* @default true
*/
withSymbol?: boolean;
}
/**
* Converts a fraction to a percentage string with optional configuration.
*
* @param {CalculableValue} molecular - The numerator of the fraction.
* @param {CalculableValue} denominator - The denominator of the fraction.
* @param {CalculateToPercentageStringOptions} [options] - Optional configuration for the result.
* @returns {string} The percentage string.
*
* @example
* ```typescript
* import { calculateToPercentageString } from '@kikiutils/node/math';
*
* // With symbol
* const percentWithSymbol = calculateToPercentageString(50, 200);
* console.log(percentWithSymbol); // Output: '25.00%'
*
* // Without symbol
* const percentWithoutSymbol = calculateToPercentageString(50, 200, { withSymbol: false });
* console.log(percentWithoutSymbol); // Output: '25.00'
*
* // With custom decimal places
* const percentCustomDecimal = calculateToPercentageString(50, 200, { decimalPlaces: 1 });
* console.log(percentCustomDecimal); // Output: '25.0%'
* ```
*/
export function calculateToPercentageString(molecular: CalculableValue, denominator: CalculableValue, options?: CalculateToPercentageStringOptions) {
const molecularDecimal = new Decimal(molecular.toString());
const denominatorDecimal = new 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;
}