user8724929
user8724929

Reputation:

javascript filesize function glitch with bytes between 1000 and 1024

So I created this function, it adapts the amount of bytes to the right binary unit. The problem I am having is that whenever a file is between 1000 and 1024 bytes it shows up as: 1.02e+3 KB. Am I doing something wrong or did I forgot to catch all exception? Thanks for the help.

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];

function grid_filesizeCellClientTemplate(bytes) {
    if (!bytes)
        return "";

    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    var size = (bytes / Math.pow(1024, Math.floor(e)));
    var unit = ce_sizeSuffixes[e];
    //bug with a size >= 1000 and < 1024
    return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';
}

Solution:

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];
function grid_filesizeCellClientTemplate(bytes) {
if (!bytes)
    return "";

var e = Math.floor(Math.log(bytes) / Math.log(1024));
var size = (bytes / Math.round(size * 1000) / 1000));
var unit = ce_sizeSuffixes[e];
//bug with a size >= 1000 and < 1024
return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';

Upvotes: 1

Views: 236

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

toPrecision outputs the number formatted to the given number of significant digits. 1010, or any number between 1000 and 1024 in your case, has 4 significant digits but you tell the code to give 3. Hence, 1.01e+3.

If you want to round the number to 3 decimal places, consider Math.round(size*1000)/1000 instead.

Upvotes: 1

Related Questions