반응형

바이트 단위 크기를 보기 좋은 단위(KB,MB,GB,TB) 크기로 출력하기

글, 수알치 오상문 

 

바이트 단위의 숫자를 보기 좋게 KB, MB, GB, TB로 변경하여 출력하는 예제입니다.


def sizefy(value):
    if value < 512000:
        value = value / 1024.0
        ext = 'KB'
    elif value < 4194304000:
        value = value / (1024*1024.0)
        ext = 'MB'
    elif value < 450359962737:
        value = value / (1024*1024*1024.0)
        ext = 'GB'
    else:
        value = value / (1024*1024*1024*1024.0)
        ext = 'TB'


    return f'{str(round(value, 2))}{ext}'

 


# 사용 예제 
value = 5000

for i in range(10): 
  print(value, 'bytes =', sizefy(value))
  value *= 10

 


[실행 결과]
5000 bytes = 4.88KB
50000 bytes = 48.83KB
500000 bytes = 488.28KB
5000000 bytes = 4.77MB
50000000 bytes = 47.68MB
500000000 bytes = 476.84MB
5000000000 bytes = 4.66GB
50000000000 bytes = 46.57GB
500000000000 bytes = 0.45TB
5000000000000 bytes = 4.55TB

반응형

+ Recent posts