Calculate Percentage
Performs various percentage-related calculations based on the specified mode.
calculatePercentage
The calculatePercentage function performs various percentage-related calculations based on the specified mode and input values. It supports operations such as computing percentages, values from percentages, original values, percentage changes, applying percentage changes, percentage differences, and inverse percentages.
Function Signature
function calculatePercentage(options: PercentageOptions): numberParameters
options(PercentageOptions): An object specifying the calculation mode, the necessary input values, and an optional rounding precision.
Modes & Parameters (Options)
All modes support an optional roundTo (number) property, which determines the number of decimal places to round the result to if it's a float. Defaults to 3.
Examples by Mode
playground.ts
Type Definitions
type PercentageOptions = (
| GetPercentOptions
| GetValueOptions
| GetOriginalOptions
| GetChangeOptions
| ApplyChangeOptions
| GetDifferenceOptions
| InversePercentageOptions
) & {
roundTo?: number;
};
interface GetPercentOptions {
mode: 'get-percent';
part: number;
total: number;
}
interface GetValueOptions {
mode: 'get-value';
percentage: number;
total: number;
}
interface GetOriginalOptions {
mode: 'get-original';
percentage: number;
value: number;
}
interface GetChangeOptions {
mode: 'get-change-percent';
oldValue: number;
newValue: number;
}
interface ApplyChangeOptions {
mode: 'apply-percent-change';
baseValue: number;
percentage: number;
}
interface GetDifferenceOptions {
mode: 'get-percent-difference';
value1: number;
value2: number;
}
interface InversePercentageOptions {
mode: 'inverse-percent';
part: number;
total: number;
}Notes
- The function ensures that inputs are valid numbers before performing calculations.
- For percentage change calculations, if the
oldValueis zero, the function returnsNaNto avoid division by zero. - It assumes that all input values are finite numbers; passing
InfinityorNaNas inputs will result inNaNoutputs.
Last updated: Sun, Jun 14, 2026 07:06:16AM (UTC)
