Skip to content

Documentation / @andrew_l/toolkit / parsePercentage

Function: parsePercentage()

parsePercentage(value): number

Safely parses a percentage value and returns a number between 0 and 100. It accepts both string and numeric input, automatically handling the '%' sign if present. If the value is not a valid percentage, it returns 0.

Parameters

value: unknown

The value to parse, which can be a string (e.g., '99%') or a number (e.g., 45).

Returns

number

A parsed percentage value, constrained between 0 and 100. If the input is invalid or cannot be parsed, it returns 0.

Examples

ts
parsePercentage('99%');
// Returns: 99
ts
parsePercentage('150%');
// Returns: 100 (clamped to the maximum allowed value)
ts
parsePercentage('50.5%');
// Returns: 50.5
ts
parsePercentage('abc');
// Returns: 0 (invalid input)
ts
parsePercentage(80);
// Returns: 80 (valid number input)