Code of the day: Converts Bytes to Simplify Units

A few days ago I noticed that my “code of the day” article was wrong. So I spent some time fixing it and provided test cases to check my work.
The main difference about this script is that it allows you to support both the SI and IEC standard and fixes a few rounding errors.

// function: getBytesWithUnit
// input: bytes (number)
// input: useSI (boolean), if true then uses SI standard (1KB = 1000bytes), otherwise uses IEC (1KiB = 1024 bytes)
// input: precision (number), sets the maximum length of decimal places.
// input: useSISuffix (boolean), if true forces the suffix to be in SI standard. Useful if you want 1KB = 1024 bytes
// returns (string), represents bytes is the most simplified form.
var getBytesWithUnit = function (bytes, useSI, precision, useSISuffix) {
	"use strict";
	if (!(!isNaN(bytes) && +bytes > -1 && isFinite(bytes))) {
		return false;
	}
	var units, obj,	amountOfUnits, unitSelected, suffix;
	units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	obj = {
		base : useSI ? 10 : 2,
		unitDegreeDiff : useSI ? 3 : 10
	};
	amountOfUnits = Math.max(0, Math.floor(Math.round(Math.log(+bytes) / Math.log(obj.base) * 1e6) / 1e6));
	unitSelected = Math.floor(amountOfUnits / obj.unitDegreeDiff);
	unitSelected = units.length > unitSelected ? unitSelected : units.length - 1;
	suffix = (useSI || useSISuffix) ? units[unitSelected] : units[unitSelected].replace('B', 'iB');
	bytes = +bytes / Math.pow(obj.base, obj.unitDegreeDiff * unitSelected);
	precision = precision || 3;
	if (bytes.toString().length > bytes.toFixed(precision).toString().length) {
		bytes = bytes.toFixed(precision);
	}
	return bytes + " " + suffix;
};




Demo: Test Script here


Want to learn more about Javascript?
Check out this “Professional JavaScript for Web Developers”.

Be Sociable, Share!

Larry Battle

Hello, I'm Larry Battle and I love to program, fix problems and discover new technologies. Check out my stackoverflow and github accounts. I also do book reviews on amazon.com. I'm not the best of writers but I do enjoy spreading my knowledge through my short blogs at bateru.com/news. So please leave some feedback. It would be greatly appreciated.

More Posts - Website

Follow Me:
Twitter