kb to mb js 1

kb to mb js

const formatBytes = (bytes, decimals = 2) => {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return (
        parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i]
    );
}

Here is what the above code is Doing:
1. We're creating a function called formatBytes that takes two parameters: bytes and decimals.
2. We're setting the default value of decimals to 2.
3. We're checking if the bytes is equal to 0. If it is, we're returning 0 Bytes.
4. We're creating a variable called k and setting it to 1024.
5. We're creating a variable called dm and setting it to decimals if decimals is less than 0, otherwise we're setting it to 0.
6. We're creating a variable called sizes and setting it to an array of strings.
7. We're creating a variable called i and setting it to the floor of the log of bytes divided by the log of k.
8. We're returning the result of the following:
- We're parsing the result of the following:
- We're dividing bytes by the power of k to the i.
- We're rounding the result to dm decimal places.
- We're concatenating a space and the value of sizes at index i.

Similar Posts