format number as gigabytes in python

To format a number as gigabytes in Python, you can use the format() function along with the '{:.2f} GB' format specifier to display the number with two decimal places followed by the unit 'GB'. Here's an example code snippet:

main.py
num_bytes = 1024 * 1024 * 1024  # one gigabyte in bytes
num_gb = num_bytes / (1024 ** 3)  # convert to gigabytes
formatted_num = '{:.2f} GB'.format(num_gb)  # format as string with 2 decimal places and 'GB' unit
print(formatted_num)  # output: '1.00 GB'
254 chars
5 lines

In this code snippet, we first define the number of bytes in one gigabyte (num_bytes). We then convert this to gigabytes by dividing by 1024 ** 3 (i.e., 1024 raised to the power of 3), which gives us num_gb. Finally, we use the format() function to format the number as a string with two decimal places and the 'GB' unit. The resulting string is stored in the variable formatted_num and printed to the console using the print() function.

related categories

gistlibby LogSnag