Format File Sizes

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write formatBytes(bytes, options) to show a file size, where bytes is a whole number of 0 or more. By default use decimal units, B, KB, MB, GB and TB, each 1000 times the one before; with options.binary set to true, use binary units, B, KiB, MiB, GiB and TiB, each 1024 times the one before. Use the largest unit the size reaches, up to TB or TiB, so 1500 is "1.5 KB" and 5000 terabytes is "5000 TB". Below one KB or KiB, show the whole number of bytes, such as "999 B". In bigger units, round to one decimal place and drop a trailing .0, so 2048 bytes is "2 KB". If rounding reaches the next step, such as 999,999 bytes rounding to 1000 KB, show it in the next unit instead: "1 MB". Put one space between the number and the unit. options may be left out.

Your code must pass

  • Shows small sizes in bytes
  • Uses decimal units with one decimal place
  • Uses binary units when asked
  • Moves up a unit when rounding reaches the next step
  • Stops at terabytes