Coding Challenge - #29: Format Byte Size

Write a function formatBytes(bytes) that converts a non-negative integer number of bytes into a human-readable string using units B, KB, MB, or GB (base 1024). Values with units larger than B should be rounded to two decimal places, omitting trailing zeros if whole (e.g., formatBytes(1536) returns '1.5 KB', formatBytes(1048576) returns '1 MB', and formatBytes(500) returns '500 B').

function formatBytes(bytes) {
  // Your code here
}

Rules:

  • Use 1024 as the byte conversion threshold.
  • Do not display trailing zeros after decimal places (e.g. ‘1.5 KB’, not ‘1.50 KB’).
  • Return ‘0 B’ when the input is 0.

Post your solution as a reply. Answer goes up in about a day.