percentOf
Calculates the numeric value representing a percentage of a total.
1/**
2 * Calculates the numeric value representing a percentage of a total.
3 *
4 * @param total - The total value.
5 * @param percent - The percentage to calculate (e.g. 17 for 17%).
6 * @returns The value corresponding to the given percent of the total.
7 */
8export function percentOf(total: number, percent: number): number {
9 return (total * percent) / 100;
10}
Clear Mathematical Intent
Expresses the concept of "X percent of Y" directly, improving readability and reducing calculation errors.
Lightweight and Fast
Uses basic arithmetic without any loops or conditionals, making it highly performant.
Reusable and Predictable
Stateless and side-effect-free, suitable for repeated use in any context.
Tests | Examples
1test('percentOf - typical percentage', () => {
2 expect(percentOf(200, 25)).toBe(50);
3});
4
5test('percentOf - zero percent', () => {
6 expect(percentOf(142, 0)).toBe(0);
7});
8
9test('percentOf - full percent (100%)', () => {
10 expect(percentOf(142, 100)).toBe(142);
11});
12
13test('percentOf - decimal percent', () => {
14 expect(percentOf(142, 17.5)).toBeCloseTo(24.85);
15});
16
17test('percentOf - over 100 percent', () => {
18 expect(percentOf(80, 150)).toBe(120);
19});
20
21test('percentOf - negative percent', () => {
22 expect(percentOf(200, -10)).toBe(-20);
23});
24
25test('percentOf - negative total', () => {
26 expect(percentOf(-100, 25)).toBe(-25);
27});
Common Use Cases
Pricing and Discounts
Calculate discount amounts or tax based on a given percentage of a total price.
UI Components
Determine progress bar fill, pie chart segments, or relative sizing based on percentage values.
Financial and Business Logic
Compute portions like commissions, tips, fees, or interest from total amounts.
Data Visualization and Reporting
Convert percentage metrics into actual values for graphical representation.
Educational Tools or Simulations
Solve percentage-based problems or simulate partial quantities in interactive tools.