Code of the day: Javascript convert bytes to KB, MB, GB, etc

Note: This uses the IEC standard. That means 1 KB = 1024, not 1000 like the SI standard.

/**
* @function: getBytesWithUnit()
* @purpose: Converts bytes to the most simplified unit.
* @param: (number) bytes, the amount of bytes
* @returns: (string)
*/
var getBytesWithUnit = function( bytes ){
	if( isNaN( bytes ) ){ return; }
	var units = [ ' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB' ];
	var amountOf2s = Math.floor( Math.log( +bytes )/Math.log(2) );
	if( amountOf2s < 1 ){
		amountOf2s = 0;
	}
	var i = Math.floor( amountOf2s / 10 );
	bytes = +bytes / Math.pow( 2, 10*i );
 
	// Rounds to 3 decimals places.
        if( bytes.toString().length > bytes.toFixed(3).toString().length ){
            bytes = bytes.toFixed(3);
        }
	return bytes + units[i];
};

Output:

console.log( getBytesWithUnit( ) );			// returns undefined.
console.log( getBytesWithUnit( 'non a number.' ) );	// returns undefined.
console.log( getBytesWithUnit( '123' ));		// returns '123 bytes'.
console.log( getBytesWithUnit( 1024 ));		// returns '1 KB'.
console.log( getBytesWithUnit( (1024 * 1024) + 1024 )); // returns '1.001 MB'.
console.log( getBytesWithUnit( 1024 * 1024 * 1024 )); // returns '1 GB'.
console.log( getBytesWithUnit( 1024 * 1024 * 64 )); // returns '64 MB'.

Update
I updated the script to support both the SI and IEC standard.
Check it out here http://bateru.com/news/2012/03/code-of-the-day-converts-bytes-to-unit/

(Page view Count: 752)