5

Not really a question but kind of a challenge..

I have this PHP function that I always use and now I need it in Javascript.

function formatBytes($bytes, $precision = 0) {
    $units = array('b', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

EDIT: Thanks to the replies I came up with something shorter, but without precision (let me know if you have some second thoughts)

function format_bytes(size){
    var base = Math.log(size) / Math.log(1024);
    var suffixes = ['b', 'KB', 'MB', 'GB', 'TB' , 'PB' , 'EB'];
    return Math.round(Math.pow(1024, base - Math.floor(base)), 0) + ' ' + suffixes[Math.floor(base)];
}
0

2 Answers 2

1

Think this is right, have not tested it:

Update: Had to fix it as there was no default for precision and I had a typo in the last line, now functional.

function formatBytes(bytes, precision) {
  var units = ['b', 'KB', 'MB', 'GB', 'TB'];
  var bytes = Math.max(bytes, 0);
  var pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
  pow = Math.min(pow, units.length - 1);
  bytes = bytes / Math.pow(1024, pow);
  precision = (typeof(precision) == 'number' ? precision : 0);
  return (Math.round(bytes * Math.pow(10, precision)) / Math.pow(10, precision)) + ' ' + units[pow];
}
Sign up to request clarification or add additional context in comments.

1 Comment

@John Giotta Apologies for the bug, I forgot to set a default for precision.
0

Tested:

function formatBytes(bytes, precision)
{
    var units = ['b', 'KB', 'MB', 'GB', 'TB'];
    bytes = Math.max(bytes, 0);
    var pwr = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
    pwr = Math.min(pwr, units.length - 1);
    bytes /= Math.pow(1024, pwr);
    return Math.round(bytes, precision) + ' ' + units[pwr];
}

2 Comments

Math.round(number, precision) I knew existed, but I slowed mine down by not using the "precision" argument as most definitions for the Javascript spec on it seem not to indicate the availability of the precision argument. So I implemented it with scaling up and then dividing.
precision is not working for me with Math.round(bytes, precision). Try bytes.toFixed(precision) instead. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.