[Python] Python format size application (converting B to KB, MB, GB, TB)

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write an application to convert bytes to kb to mb to gb to tb. Here's what I have so far:

    def size_format(b):
    if b < 1000:
    return '%i' % b + 'B'
    elif 1000 <= b < 1000000:
    return '%.1f' % float(b/1000) + 'KB'
    elif 1000000 <= b < 1000000000:
    return '%.1f' % float(b/1000000) + 'MB'
    elif 1000000000 <= b < 1000000000000:
    return '%.1f' % float(b/1000000000) + 'GB'
    elif 1000000000000 <= b:
    return '%.1f' % float(b/1000000000000) + 'TB'


    The problem is, when I try the application I get everything after the decimal zeroing out. example size_format(623) yields '623B' but with size_format(6200), instead of getting '6.2kb' I'm getting '6.0kb'. Any ideas why?

    Continue reading...

Compartilhe esta Página