All files / utils formatBytes.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

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 2024x                 11x 6x   5x       5x 5x    
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
 
/**
 * 格式化字节数,以 1024 作为千字节数。
 *
 * @param value 要格式化的字节数
 * @returns 返回结果
 */
export function formatBytes(value: number): string {
  if (value < 1024) {
    return `${Number(value.toFixed(2))} ${units[0]}`
  }
  const exponent = Math.min(
    Math.floor(Math.log(value) / Math.log(1024)),
    units.length - 1,
  )
  value = Number((value / Math.pow(1024, exponent)).toFixed(2))
  return `${value} ${units[exponent]}`
}