Skip to content

Instantly share code, notes, and snippets.

@vikynandha-zz
Last active December 25, 2015 00:28
Show Gist options
  • Save vikynandha-zz/6887706 to your computer and use it in GitHub Desktop.
Save vikynandha-zz/6887706 to your computer and use it in GitHub Desktop.
Format file size in bytes to human-readable string
function fileSizeFormat( num_bytes ) {
if ( ! num_bytes ) return '0 bytes';
typeof num_bytes == 'number' || ( num_bytes = parseFloat( num_bytes ) );
if ( isNaN( num_bytes ) ) return '';
var i = -1;
var byteUnits = [ 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
do {
num_bytes = num_bytes / 1000;
i++;
} while ( num_bytes > 999 && i < byteUnits.length - 1 );
return ( num_bytes == Math.floor(num_bytes) ? num_bytes :
Math.max( num_bytes, 0.1 ).toFixed( 1 ) ) +
}
// Jasmine specs
describe( 'fileSizeFormat', function() {
it(' should convert to appropriate unit', function() {
var base = 1.3, i,
byteUnits = [ 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
for( i=1; i<=byteUnits.length; i++ ) {
expect( fileSizeFormat( 1.3 * Math.pow( 1024, i ) ) )
.toBe( base + ' ' + byteUnits[i - 1] );
}
});
it('should parse float if argument is a string', function() {
expect( fileSizeFormat( '1000' ) ).toBe( '1 kB' );
});
it('should work for 0', function() {
expect( fileSizeFormat( 0 ) ).toBe( '0 bytes' );
});
it('should work for too large numbers', function() {
expect( fileSizeFormat( 1.3 * Math.pow( 1000, 9 ) ) ).toBe( 1.3 * 1024 + ' YB' );
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment