Hacker News new | past | comments | ask | show | jobs | submit login

Coincidentally I had to write this today, and perplexingly none of the answers on that popular question seem to be as efficient and readable as what I wrote:

  function prettyPrintBytesSI(x: number): string {
    const magnitude = Math.abs(x)
    if (magnitude < 1e3) return `${x} B`
    else if (magnitude < 1e6) return `${x/1e3} kB`
    else if (magnitude < 1e9) return `${x/1e6} MB`
    else if (magnitude < 1e12) return `${x/1e9} GB`
    else if (magnitude < 1e15) return `${x/1e12} TB`
    else if (magnitude < 1e18) return `${x/1e15} PB`
    else return `${x} B`
  }



Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: