js format file size, output as a string tool with units

/**
		 * Format file size, output as a string with units
		 * @method formatSize
		 * @grammar formatSize( size ) => String
		 * @grammar formatSize( size, pointLength ) => String
		 * @grammar formatSize( size, pointLength, units ) => String
		 * @param {Number} size file size
		 * @param {Number} [pointLength=2] The exact number of decimal points.
		 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] Array of units. Specified from bytes, to kilobytes, all the way up. If only K (kilobytes) is specified in the unit array, and the file size is greater than M, the output of this method will still display the number of K.
		 * @example
		 * console.log( formatSize( 100 ) );    // => 100B
		 * console.log( formatSize( 1024 ) );    // => 1.00K
		 * console.log( formatSize( 1024, 0 ) );    // => 1K
		 * console.log( formatSize( 1024 * 1024 ) );    // => 1.00M
		 * console.log( formatSize( 1024 * 1024 * 1024 ) );    // => 1.00G
		 * console.log( formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) );    // => 1024MB
		 */
		formatSize = function(size, pointLength, units) {
			var unit;
			units = units || [ 'B', 'K', 'M', 'G', 'TB' ];
			while ((unit = units.shift()) && size > 1024) {
				size = size / 1024;
			}
			return (unit === 'B' ? size : size.toFixed(pointLength || 2))
					+ unit;
		};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326399789&siteId=291194637