Programming from zero

Convert disk usage in bytes to GB

easyNumbers and strings Must-do

Problem statement

Tools like df and cloud APIs often report sizes in bytes, which are hard to read. Given used_bytes = 5000000000, convert it to gigabytes (1 GB = 1024 x 1024 x 1024 bytes), round to 2 decimal places, and print:

4.66 GB

Examples

Example 1

Input: used_bytes = 5000000000

Output: 4.66 GB

Explanation: 5000000000 / 1073741824 is about 4.6566, which rounds to 4.66.

Hints

Approach

Optimal

First compute how many bytes are in one gigabyte: 1024 ** 3, where ** is the power operator. Dividing used_bytes by that number with / gives a float such as 4.656612873077393. The built-in round(value, 2) rounds it to two decimal places. Finally an f-string adds the unit. Storing the conversion factor in a named variable like BYTES_PER_GB makes the code easier to read than a bare 1073741824.

Python
used_bytes = 5000000000
BYTES_PER_GB = 1024 ** 3
used_gb = round(used_bytes / BYTES_PER_GB, 2)
print(f"{used_gb} GB")

Follow-up questions

  • Also print the size in MB.
  • Given a total_bytes value too, print the percentage used, rounded to 1 decimal place.

Frequently asked questions

Both exist. Strictly, 1024 x 1024 x 1024 bytes is a gibibyte (GiB), which is what most operating systems show; disk vendors use 1000 x 1000 x 1000. Pick one, and label it clearly so nobody compares mismatched numbers.

/ gives a decimal result (7 / 2 is 3.5). // divides and drops the fraction (7 // 2 is 3). For sizes you usually want / plus round.