Tuesday, July 17, 2012

Bytes to gigs, megs, kilos, and bytes

A units-to-readable conversion. My usage wraps this with a check for zero or null bytes and skips this function altogether.

function convertBytesGMKB(bytes){
 try{     
  var message = "";
  var gigs = Math.floor(bytes/Math.pow(1024,3));
  var divisorForMegs = bytes % Math.pow(1024,3);
  var megs = Math.floor(divisorForMegs / Math.pow(1024,2));
  var divisorForKilos = divisorForMegs % Math.pow(1024,2);
  var kilos = Math.floor(divisorForKilos / 1024);
  var divisorForBytes = divisorForKilos % 1024;
  var finalBytes = divisorForBytes;
  message = ((gigs > 0)?gigs+"g ":"")+((megs > 0)?megs+"m ":"")+((kilos > 0)?kilos+"k ":"")+finalBytes+"b";
  return message;
 }catch(e){
  console.log('convertBytesGMKB error: ', e);
 }
}

var content = convertBytesGMKB(Number(value));

No comments:

Post a Comment