Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Bytes into Gigabytes with javascript math

My web application allows users to upload files. I am able to find the size of these files in bytes. However I need to convert this number to gigabytes with javascript on the back-end. Does anyone know the formula and how to execute this task with javascript ?

For example: right now my file size is 626581571 bytes.

like image 387
Nodedeveloper101 Avatar asked Jul 15 '26 09:07

Nodedeveloper101


2 Answers

1 kilobyte = 1024 bytes, 1 megabyte = 1024 kilobytes, 1 gigabyte = 1024 megabytes, respectively file_size_gb = 626581571 / 1024 / 1024 / 1024.

Or as said in the comment below, file_size_gb = 626581571 / Math.pow(1024, 3)

like image 177
Oleksandr Verhun Avatar answered Jul 19 '26 20:07

Oleksandr Verhun


1 KB = 1000 Bytes

It's basic math:

1 GB = 1 000 MB = 1 000 000 KB = 1 000 000 000 B

626 581 571 B = 0.626 GB

Thus, you just need to divide by 109

function byteToGigaByte(n) {
    return  (n / Math.pow(10,9));
}

1 KiB = 1024 Bytes

Perhaps you meant gibibyte instead of gigabyte?

Once again, it's basic math:

1 GiB = 1024 MiB = 1024 * 1024 KiB = 1024 * 1024 * 1024 B
      = 1073741824 B

626 581 571 B = 0.583 GiB

This time, you need to divide by 230

function byteToGibiByte(n) {
    return  (n / Math.pow(2,30));
}

Note the slight difference between gigabyte and gibibyte: 1 GB = 0.931 GiB.

like image 37
Yuriko Avatar answered Jul 19 '26 22:07

Yuriko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!