0

I'm using Handlebar template in my backbone application.

In some part of my application, I'm getting size of a file in bytes. And I want to show that in the front-end, but not in bytes but in Byes, KB, MB, GB depending on the size of the file.

I can easily do that using if else block and the byte value of KB, MB, GB. e.g

HandleBars.registerHelper('filesize', function(bytes) {
        if(bytes < 1024)
        return bytes+'Bytes'
        else if(bytes >= 1024 && bytes < 1048576)
        return (bytes/1024) + 'KB'
    });

Can anybody suggest me, the better method to do this.

  • 1
    possible duplicate of [Correct way to convert size in bytes to KB, MB, GB in Javascript](http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript) – Shital Shah Jun 08 '14 at 04:52

1 Answers1

-1

Yeah you can do that using the Math.log & Math.pow function of Javascript. That'll minimize the function.

HandleBars.registerHelper('filesize', function(bytes) {
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        if (bytes == 0) return '0 Bytes';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
    });
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
  • 4
    You should give credit to original answer at http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript – Shital Shah Jun 08 '14 at 04:51