Categories: Tutorials

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”.

Larry Battle

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

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