Format bytes to kilobytes, megabytes, gigabytes

Scenario: the size of various files are stored in a database as bytes. What’s the best way to format this size info to kilobytes, megabytes and gigabytes? For instance I have an MP3 that Ubuntu displays as “5.2 MB (5445632 bytes)”. How would I display this on a web page as “5.2 MB” AND have files less than one megabyte display as KB and files one gigabyte and above display as GB?

28 Answers
28

Leave a Comment