Skip to main content
Programming from zero

Convert disk usage in bytes to GB

easyTypes and operators

Problem statement

Disk usage often comes back from a system call in raw bytes, a huge number that's hard to read. To turn bytes into GB, divide by 1024 * 1024 * 1024 (1024³), since that's how many bytes fit in one GB. This is the binary convention, 1 GB = 1024³ bytes (strictly called a GiB). Some tools use 1000³ instead, so always check which one your tool reports.

Common mistake: dividing two whole numbers and getting a whole number back, instead of a decimal.

TEXT
Wrong (Java/C++): int gb = diskBytes / bytesPerGB;

In Java and C++, dividing an int by an int throws away anything after the decimal point, so 5368709120 / 1073741824 gives 4, not 4.5. Declaring the values as double first fixes it, since dividing a double by anything always keeps the decimal part. Python doesn't have this trap, / always gives a decimal result there regardless of the input types.

Your task: given diskBytes = 5368709120, convert it to GB and print the result rounded to 2 decimal places.

Expected output:

TEXT
5.00

Approach

Every language does the same division, then rounds to 2 decimal places, they just spell "round to 2 places" differently:

  • Python uses an f-string format, f"{gb:.2f}", where .2f means "2 digits after the decimal point".
  • Java doesn't have a one-step rounder for printing, so String.format("%.2f", value) builds the rounded text directly.
  • C++ uses std::fixed and std::setprecision(2) on the output stream, from <iomanip>.
disk_bytes = 5368709120
bytes_per_gb = 1024 * 1024 * 1024
gb = disk_bytes / bytes_per_gb
print(f"{gb:.2f}")