pythonhumanize

Python humanize.naturalsize() remove trailing 0's in the fraction


Is it possible to get the output of

1M
1.01M

by changing the format's value in the following code?

import  humanize

format = "%.2f"
raw1 = 1_048_576;
raw2 = 1_058_576

print(humanize.naturalsize(raw1, format=format, gnu=True));
print(humanize.naturalsize(raw2, format=format, gnu=True));

Solution

  • One possible solution could be post-process the string afterwards:

    import re
    
    import humanize
    
    
    def my_format(num, fmt="%.2f"):
        n = humanize.naturalsize(num, format=fmt, gnu=True)
        return re.sub(r"\.0+(?=\D)", "", n)
    
    
    raw1 = 1_048_576
    raw2 = 1_058_576
    
    print(my_format(raw1))
    print(my_format(raw2))
    

    Prints:

    1M
    1.01M