Skip to content

Function: safePercentage() ​

ts
function safePercentage(
   part, 
   total, 
   fallback?): number;

Safe variant of percentage: returns fallback (default 0) instead of throwing when total is zero or inputs are non-finite. percentage 的安全版本:当 total 为零或输入非有限时返回 fallback(默认 0),而非抛错。

Parameters ​

ParameterTypeDefault valueDescription
partnumberundefinedPartial value / 部分值
totalnumberundefinedWhole value / 总值
fallbacknumber0Returned when total <= 0 or inputs are non-finite (default 0) / total 为零或输入非有限时返回(默认 0)

Returns ​

number

Percentage, or fallback / 百分比,或 fallback

Example ​

ts
safePercentage(30, 200) // => 15
safePercentage(10, 0) // => 0
safePercentage(10, 0, -1) // => -1

Since ​

1.3.0

Released under the MIT License.