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

38 Views Asked by At

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));
2

There are 2 best solutions below

1
On BEST ANSWER

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
1
On

No, any change to the format will apply to both outputs. Changing format to below will get the format of 1M but again, it applies to both.

format = "%1.0f"