Skip to content
On this page

formatToFixed方法

Hidden Title

基础用法:formatToFixed(22)

基础用法

通常用法

说明

formatToFixed 用于把数字或带单位的数字字符串格式化为固定小数位文本,并可追加前缀、后缀、千分位或移除原单位。它适合金额、百分比、容量数值等展示场景。

调用形式

ts
formatToFixed(value)
formatToFixed(value, digit)
formatToFixed(value, options)
formatToFixed(value)
formatToFixed(value, digit)
formatToFixed(value, options)

参数说明

参数类型必填默认值说明
valueunknown-要格式化的值。支持数字、数字字符串、带单位的数字字符串,如 22 TB
digitnumber2第二个参数直接传数字时,表示保留的小数位数。
optionsFormatToFixedOptions{}第二个参数传对象时,用于控制完整格式。

FormatToFixedOptions 字段:

字段类型默认值说明
digitnumber2保留的小数位数。
prefixstring''结果前缀,例如 $
suffixstring''结果后缀,例如 %
unitbooleantrue是否保留原始值里的单位。
thousandsbooleanfalse是否给数值部分添加千分位分隔符。

返回值

返回格式化后的字符串。如果输入无法按数字规则解析,会返回 String(value)

常用场景

ts
formatToFixed(22)
// '22.00'

formatToFixed(22.1234, 3)
// '22.123'

formatToFixed('22 TB', { unit: false, prefix: '$' })
// '$22.00'

formatToFixed(222222, { digit: 2, thousands: true })
// '222,222.00'
formatToFixed(22)
// '22.00'

formatToFixed(22.1234, 3)
// '22.123'

formatToFixed('22 TB', { unit: false, prefix: '$' })
// '$22.00'

formatToFixed(222222, { digit: 2, thousands: true })
// '222,222.00'

注意事项

unit: false 只会移除输入值里原本携带的单位,不会影响 suffix。如果需要展示百分号,使用 suffix: '%'

函数源码

formatToFixed

来源:packages/utils/src/format.ts

/**
 * 按指定小数位格式化数字,并可附带前后缀、单位和千分位。
 *
 * @param value 需要格式化的值。
 * @param options 小数位数或配置项。
 * @returns 格式化后的字符串。
 *
 * @example
 * formatToFixed('22.1', 2)
 * // => '22.10'
 *
 * @example
 * formatToFixed('22 TB', { digit: 2, unit: false, prefix: '$' })
 * // => '$22.00'
 */
export function formatToFixed(value: unknown, options?: FormatToFixedOptions | number): string {
  if (typeof options === 'number') {
    options = { digit: options }
  }

  const finalOptions: Required<FormatToFixedOptions> = {
    digit: 2,
    prefix: '',
    suffix: '',
    unit: true,
    thousands: false,
    ...options,
  }
  const { digit, prefix, suffix, unit, thousands } = finalOptions

  const matches = ('' + value).match(/^([\d,]+)(\.?)(\d+)?(\D+)?$/)
  if (!matches) {
    return String(value)
  }

  const numericString = matches[1].replace(/\D/g, '')
  const decimalString = matches[3] ? `.${matches[3]}` : ''
  let finalUnit = matches[4] || ''
  let res = numericString

  if (isStringNumber(numericString) || isNumber(numericString)) {
    res = Number(numericString + decimalString).toFixed(digit)
  }

  if (thousands) {
    res = String(formatThousands(res))
  }

  if (!unit) {
    finalUnit = ''
  }

  return `${prefix}${res}${finalUnit}${suffix}`
}

思云博智私有前端组件库