Bytes to human string

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Converts a number in bytes to a human-readable string.

    const prettyBytes = (num: number, precision: number = 3, addSpace: boolean = true) => {
      const UNITS: Array<string> = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
      const exponent: number = Math.min(
        Math.floor(Math.log10(num < 0 ? -num : num) / 3),
        UNITS.length - 1
      );
      const n: number = Number(
        ((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)
      );
      return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.