How to format very small number with python?

Viewed 58

I am looking at cryptocurrencies prices. When converted into bitcoin or sometimes even in usd, I get very small amount from the api I use.

This is the type of response I can get:

  • 7.2e-05
  • 4.89686e-07

Here is what I do:

answer_from_api = 7.2e-05
formatting = format(answer_from_api, "f")
print(formatting)
>>>> 0.000072

However, I would like to have a separator to get something easier to read, like so:

price = 0.000 072 And I would like it to work for very small numbers like this one: 4.89686e-07 but also not "break" higher number like 150.22

Any ideas? Best,

2 Answers

I don't think there is anything in the format language to accommodate this but you can easily write your own helper function.

def format_with_space(number, decimals=6):
    as_str = f'{{:.{decimals}f}}'.format(number)
    chunks = []
    start_chunk = as_str.find('.') + 4
    chunks.append(as_str[:start_chunk])
    for i in range(start_chunk, len(as_str), 3):
        chunks.append(as_str[i:i+3])
    return ' '.join(chunks)

print(format_with_space(7.2e-05)) # 0.000 072
print(format_with_space(150.22, decimals=3)) # 150.220
print(format_with_space(7.2e-05, decimals=20)) # 0.000 072 000 000 000 000 00

So, there could be many ways around this. What I would do is:

def format_small(x, sep_loc=3):
    # check if number is not really small (no 'e' in string representation)
    if "e" not in str(x):
        # return the string representation
        return str(x)
    
    # get the number of decimals
    dec = int(str(x).split("-")[1])-1

    # for really small numbers add a space at the position indicated by sep_loc
    s = format(x, f".{dec+sep_loc-1}f")
    return s[:-sep_loc] + ' ' + s[-sep_loc:]

print(format_small(7.2e-05)) # prints 0.000 072
print(format_small(150.21)) # prints 150.21
print(format_small(0.12)) # prints 0.12
print(format_small(4.89686e-07)) # prints 0.00000 049
Related