Michael
Michael

Reputation: 245

Convert KB to MB and GB

How to setup this function to get results only in MB or GB in this format?

function formatBytes(bytes, decimals, binaryUnits) {
    if (bytes == 0) {
        return '0 Bytes';
    }
    var unitMultiple = binaryUnits ? 1024 : 1000; 
    var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
        ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
        :
        ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
    return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}

Currently, when I use this function I get a result of 40000 / 12000 KB, and I would like a result of 40 / 12 MB.

These are my input parameters, this is how I want to get the result:

1000000000/1000000000 -> 1/1 Gbits  
40000/12000 -> 40/12 MBits

Upvotes: 0

Views: 321

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

It may be a little less optimal in a sense that i do multiple divisions rather than a single one, but recursion approach seems relatively easy to implement

function formatBytes(bytes, decimals=0, binaryUnits=true) {
  return format(
    bytes,
    binaryUnits ? 1024 : 1000,
    binaryUnits ?
      ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']:
      ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
  )

  function format(value, divisor, [currentLabel, ...otherLabels]) {
    if (value < divisor) return `${value.toFixed(decimals || 0)} ${currentLabel}`;
    
    return format(value / divisor, divisor, otherLabels);
  }
}



console.log(formatBytes(1000,2,true));
console.log(formatBytes(10000,2,true));
console.log(formatBytes(100000,2,true));
console.log(formatBytes(1000000,2,true));
console.log(formatBytes(10000000,2,true));
console.log(formatBytes(100000000,2,true));
console.log(formatBytes(1000000000,2,true));

Upvotes: 1

Related Questions