convert Bytes into Gigabytes with javascript math
Asked Answered
P

2

7

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.

Pietra answered 20/11, 2015 at 23:20 Comment(4)
The value you gave is only 597.55MB. Do you want that to be displayed as a gb value?Rudder
@jeff : The value he gave is 626.58 MB, or 597.55 MiB. :)Sibley
@Yuriko, OS (windows at least) use the value of 1024 bytes not the faux 1000 that seems to have crept into the industry.Rudder
@jeff, "kilo-" has always been "a thousand". Kilometer = 1000 meters. Kilogram = 1000 grams. So the "faux" 1000 is not faux at all. Thinking "kilo-" changes its meaning to 1024 when it comes to bytes is just ignorance or stupidity.Misstate
O
9

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)

Oriel answered 20/11, 2015 at 23:23 Comment(3)
Or var file_size_gb = 626581571 / Math.pow(1024, 3)Hoosegow
Actually, depending on the system and manufacturer, it might be 1000 and not 1024 (but both could be possible)Contreras
He asked for Gigabytes (GB) and not Gigibytes (GiB).Sibley
S
7

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.

Sibley answered 20/11, 2015 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.