All files / utils formatNumber.ts

100% Statements 16/16
100% Branches 13/13
100% Functions 1/1
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                                        52x   52x   52x 39x 39x 42x 42x   39x     52x 13x 13x 11x 11x   13x     52x       52x    
/**
 * 格式化数字选项。
 */
export interface FormatNumberOptions {
  /**
   * 整数部分的千分位分隔符。
   *
   * @default ','
   */
  thousandsSeparator?: string
 
  /**
   * 小数部分的千分位分隔符。
   *
   * @default ''
   */
  thousandthsSeparator?: string
}
 
/**
 * 格式化数字。
 *
 * @param value 要格式化的数字
 * @param options 选项
 * @returns 返回格式化后的数值
 * @example
 * ```typescript
 * formatNumber(1314.56789) // => '1,314.56789'
 * formatNumber(1314.56789, { thousandsSeparator: ' ' }) // => '1 314.56789'
 * formatNumber(1314.56789, { thousandthsSeparator: ',' }) // => '1,314.567,89'
 * ```
 */
export function formatNumber(
  value: number,
  options?: FormatNumberOptions,
): string {
  const { thousandsSeparator = ',', thousandthsSeparator = '' } = options || {}
 
  let [integer, decimal = ''] = String(Math.abs(value)).split('.')
 
  if (thousandsSeparator !== '') {
    let result = ''
    while (integer.length > 3) {
      result = `${thousandsSeparator}${integer.slice(-3)}${result}`
      integer = integer.slice(0, integer.length - 3)
    }
    integer = `${integer}${result}`
  }
 
  if (thousandthsSeparator !== '') {
    let result = ''
    while (decimal.length > 3) {
      result = `${result}${decimal.slice(0, 3)}${thousandthsSeparator}`
      decimal = decimal.slice(3)
    }
    decimal = `${result}${decimal}`
  }
 
  const numeral = `${value < 0 ? '-' : ''}${integer}${
    decimal ? `.${decimal}` : ''
  }`
 
  return numeral
}