Skip to content

Instantly share code, notes, and snippets.

@lanqy
Created March 19, 2013 03:05
Show Gist options
  • Save lanqy/5193417 to your computer and use it in GitHub Desktop.
Save lanqy/5193417 to your computer and use it in GitHub Desktop.
JavaScript To Convert Bytes To MB, KB, Etc
// from http://scratch99.com/web-development/javascript/convert-bytes-to-mb-kb/
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if (i == 0) return bytes + ' ' + sizes[i];
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
@artembelik
Copy link

  const units = ["byte", "kilobyte", "megabyte", "terabyte", "petabyte"];

you lost "gigabyte"

@weroro-sk
Copy link

@gynekolog I implemented a simple word declension for the word "byte".

export const convertBytes = (bytes: number, options: { useBinaryUnits?: boolean; decimals?: number } = {}): string => {
    const {useBinaryUnits = false, decimals = 2} = options;

    if (decimals < 0)
        throw new Error(`Invalid decimals ${decimals}`);

    const declension = <T extends unknown>(num: number, dictionary: T[]): T =>
        (num = Math.abs(num)) === 1
            ? dictionary[1]
            : (num > 1 && num < 5)
                ? dictionary[2]
                : dictionary[0];

    const base = useBinaryUnits ? 1024 : 1000;
    const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(base));
    const value = bytes / Math.pow(base, i);
    const units = useBinaryUnits
        ? [["Bytes", "Byte", "Bytes"], "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
        : [["Bytes", "Byte", "Bytes"], "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

    let unit = units[i];

    return `${value.toFixed(decimals)} ${Array.isArray(unit) ? declension(value, unit) : unit}`;
}

Example:

convertBytes(0); // 0 Bytes
convertBytes(1); // 1 Byte
convertBytes(2); // 2 Bytes
convertBytes(3); // 3 Bytes
convertBytes(6); // 6 Bytes
convertBytes(987); // 987 Bytes
convertBytes(34523465); // 34.52 MB

I'm from Slovakia, so in my case it would be:

const units = useBinaryUnits
    ? [["Bajtov", "Bajt", "Bajty"], "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
    : [["Bajtov", "Bajt", "Bajty"], "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
convertBytes(0); // 0 Bajtov
convertBytes(1); // 1 Bajt
convertBytes(2); // 2 Bajty
convertBytes(3); // 3 Bajty
convertBytes(4); // 4 Bajty
convertBytes(5); // 5 Bajtov
convertBytes(6); // 6 Bajtov
convertBytes(987); // 987 Bajtov
convertBytes(34523465); // 34.52 MB

@gynekolog
Copy link

@weroro-sk Good point, thanks for sharing! I gave it a try my way just for fun. The code uses Intl.PluralRules, but the whole function is more robust now. Feel free to check it out.

@brianmontanaocient
Copy link

Shouldn't 999999999 return 1 GB and not 1000 MB, since 1000000000 returns 1 GB.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment