Anil Namde
Anil Namde

Reputation: 6618

How to write this JS function in best(smartest) way?

I would like to write the function which takes file size in bytes(7762432) and return value in user readable format (7,762,432 bytes).

function(fileSizeBytes){
    // mind blowing logic :)
    return userReadable;
}

I have done it using old school string split way, but i am just curious if there exist way that can blow my head and make me scream with "O god it can be done this way too !!"

Upvotes: 0

Views: 1090

Answers (8)

guido
guido

Reputation: 19224

one line function:

function formatFileSizeBytes(size) {
    return size.replace(/(\d)(?=(\d{3})+$)/g, "$1,");
}

some testing:

for (var i = 0; i <= "123456789".split('').length; i++) {  
    alert(formatFileSizeBytes(a.slice(0,i).join(''))); 
}

Upvotes: 6

kirilloid
kirilloid

Reputation: 14314

Ok, there should be some ENTERPRISE solution for this with intensive i18n support

var numberLocaleFormat = (function() {
  var cache = {};
  return (function (separator, grouping, groupingAdd) {
    separator = separator || ",";
    grouping = grouping || 3;
    groupingAdd = groupingAdd || grouping;
    var key = grouping + "+" + groupingAdd + "/" + separator;
    if (key in cache) return cache[key];
    return (cache[key] = function(number){
      var str = [], number = number.toString();
      var separatorIndex = grouping;
      for (var i = number.length-1, idx = 0; i >= 0; i--, idx++) {
        str.push(number.charAt(i));
        if ((idx == separatorIndex-1) && i) {
           separatorIndex += groupingAdd;
           str.push(separator);
        }
      }
      return str.reverse().join('');
    });
  });
})();

Usage:

numberLocaleFormat()(1234578); // "12,345,678", America
numberLocaleFormat(" ")(12345678); // "12 345 678", Europe
numberLocaleFormat(",",4)(12345678); // "1234,5678", Japan
numberLocaleFormat(",", 3, 2)(12345678); // "1,23,45,678", India

Upvotes: 1

Martijn
Martijn

Reputation: 13632

In Internet Explorer and Firefox, you can do return Number(fileSizeBytes).toLocaleString();.

Unfortunately, Google Chrome, Safari and Opera don’t play nice with this. They just return the same as toString().

Upvotes: 0

erickb
erickb

Reputation: 6299

This one should work if you have restriction on using an array or regex.

function comma_separate(num) {
    var comma = Math.floor((num.length) / 3);
    var offset = (num.length) % 3;
    var result = '';
    if(offset > 0) {
        result = num.substr(0,offset);
    }

    for(var i=0; i<comma; i++) {
        result = result ? result + ',' : '';
        result = result + num.substr(i*3,3);
    }

    return result;
}

tested here

Upvotes: -1

Thai
Thai

Reputation: 11372

One liner:

function(fileSizeBytes){
    return fileSizeBytes.toString(10).split('').reverse().join('').replace(/(...)/g,'$1,').replace(/,$/,'').split('').reverse().join('') + ' bytes';
}

Upvotes: 1

pleasedontbelong
pleasedontbelong

Reputation: 20102

How about using the php.js library?? number_format() function.. the doc says that the function is standalone

=P i wont break my head to do something that's already done

Upvotes: 0

SLaks
SLaks

Reputation: 888303

I wrote this function four years ago:

function formatNumber(x) { 
    if(!isFinite(x)) return x.toString();
    var str         = Math.abs(x).toString();
    if(str.indexOf("e") != -1) return x.toString();
    var decimalPos  = str.indexOf(".");
    var decimal;

    if(decimalPos == -1)
        decimal = "";
    else {
        decimal = str.substring(decimalPos);
        str = str.substring(0, decimalPos);
    }
    if(str.length < 4) return x.toString();

    var start = str.substr(0, str.length % 3);
    if(start.length != 0) {
        str = str.substr(start.length)
        start += ",";
    }
    if(x < 0) start = "-" + start;

    var segments = new Array(Math.ceil(str.length / 3.0));
    for(var i = 0; i < str.length; i += 3) {
        segments[i / 3] = str.substr(i, 3);
    }

    return start + segments.join() + decimal;
};

Upvotes: 0

Robby Pond
Robby Pond

Reputation: 73494

function addCommas(value) {
    var regex = /^(\d+)(\d{3}[\.]?.*)$/;
    while (regex.exec(value)) {
        value= RegExp.$1
                ? RegExp.$1 + ',' + RegExp.$2
                : RegExp.$2;
    }
    return value;
}

Upvotes: 6

Related Questions