Search code examples
pythonformattingcurrency

How to format currency in its most readable form python


So I was trying to format currency from some floats which are very large numbers e.g.

spendings = [1204343.65, 1000000.01, 2310.08, 5.82]

Here for example the most readable forms might be:

[$1.2M, $1M, $2.31K, $5.82] 

So what would be the most suitable way for this. locale and python-money cannot do the required formatting as they do put commas but compaction cannot be achieved by them. So is there a way I can do this so that it is in its most readable form. I came across many many answers on StackOverflow as well but none actually answers what I am trying to achieve.


Solution

  • There isnt gonna be always a way. But you have to find a way:

    def human_format(num):
        num = float('{:.3g}'.format(num))
        magnitude = 0
        while abs(num) >= 1000:
            magnitude += 1
            num /= 1000.0
        return '${}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
    

    Hence applying it to the list as follows:

    spendings = [1204343.65, 1000000.01, 2310.08, 5.82]
    [human_format(i) for i in spendings]
    

    produces:

    ['$1.2M', '$1M', '$2.31K', '$5.82']
    

    P.S. Some SO answer actually helped in this function. I cannot find it but will lik it as soon as I do