Skip to content

Instantly share code, notes, and snippets.

@zulhfreelancer
Created January 8, 2015 15:02
Show Gist options
  • Save zulhfreelancer/b7ebc4101d2b0a840e6e to your computer and use it in GitHub Desktop.
Save zulhfreelancer/b7ebc4101d2b0a840e6e to your computer and use it in GitHub Desktop.
Bytes to Terabyte (TB), Gigabyte (GB), Megabyte (MB) & Kilobyte (KB) Javascript // Demo: http://jsfiddle.net/5xzLw9dt/
<span id="bytes"></span> = <span id="converted"></span>
var x = 100000000000000;
var result = formatSizeUnits(x);
function formatSizeUnits(bytes) {
if (bytes >= 100000000000000) {
bytes = (bytes / 100000000000000).toFixed(0) + ' TB';
} else if (bytes >= 1000000000) {
bytes = (bytes / 1000000000).toFixed(0) + ' GB';
} else if (bytes >= 1000000) {
bytes = (bytes / 1000000).toFixed(0) + ' MB';
} else if (bytes >= 1000) {
bytes = (bytes / 1000).toFixed(0) + ' KB';
} else if (bytes > 1) {
bytes = bytes + ' bytes';
} else if (bytes == 1) {
bytes = bytes + ' byte';
} else {
bytes = '0 byte';
}
return bytes;
}
document.getElementById('bytes').innerHTML = x + ' bytes';
document.getElementById('converted').innerHTML = result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment