Percent 百分比

提供百分比格式化和计算的工具函数。

安装

npm
yarn
pnpm
bun
deno
npx shadcn@latest add https://codebase.anyask.dev/r/utils-percent.json

formatPercent

将数值转换为百分比形式,可指定小数位数。

功能特点

  • 自动将数值乘以 100
  • 支持指定小数位数
  • 自动处理空值和 NaN

使用示例

calculatePercentage

计算两个数值的百分比(numerator / denominator * 100),可指定小数位数。

功能特点

  • 支持任意数值类型的输入
  • 自动处理空值情况
  • 分母为 0 时:分子为 0 返回 0,否则返回 null

使用示例

API 参考

通用类型

type FormatNumberInput = string | number | null | undefined;

函数签名

函数签名
formatPercent(value: FormatNumberInput, percent?: number) => string | null
calculatePercentage(numerator?: FormatNumberInput, denominator?: FormatNumberInput, percent?: number) => string | number | null