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/
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
Good stuff Larry, thanks!
Thks, but what about the opposite ?
pass a value with a unit, and convert it to bytes :>
Hi Larry, thanks for the code. This saves my time ;)
Keep making useful things Bro!