Number/Since
1.38.0percentage
Calculates a percentage of a numeric value.
percentage(value, percent):numberParameters
valuenumberrequiredThe base value from which the percentage is calculated.
percentnumberrequiredThe percentage to calculate from the value.
Returns
numberReturns the calculated percentage of the given value.
Errors
Throws a RangeError if value is NaN.
Throws a RangeError if percent is NaN.
Examples
01
Basic usage
Calculates 25% of 200.
TypeScript
const result = percentage(200, 25);
console.log(result);
// 5002
50 percent
Calculates half of a value.
TypeScript
console.log(percentage(80, 50));
// 4003
100 percent
100% of a value returns the original value.
TypeScript
console.log(percentage(150, 100));
// 15004
Zero percent
0% of a value returns 0.
TypeScript
console.log(percentage(500, 0));
// 005
Decimal percentage
The percent argument can be a decimal value.
TypeScript
console.log(percentage(200, 12.5));
// 2506
Negative percentage
Negative percentages are calculated normally.
TypeScript
console.log(percentage(200, -10));
// -2007
Percentage above 100
Percentages greater than 100 are supported.
TypeScript
console.log(percentage(200, 150));
// 30008
Negative value
The calculation also works with negative values.
TypeScript
console.log(percentage(-200, 25));
// -5009
NaN value
A NaN value is rejected.
TypeScript
percentage(NaN, 25);
// RangeError: percentage: value must not be NaN10
NaN percentage
A NaN percentage is rejected.
TypeScript
percentage(200, NaN);
// RangeError: percentage: percent must not be NaNBuilt with@cyref/js·Official documentation