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/

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

View Comments

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago