How to format numbers as strings (1k, 2M...) without rounding up in python?

dereks :

I'm trying to round floor to int or to 1 decimal for non-zero float with letters k, M, B....

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

Now this function returns as expected in this case:

human_format(1294)
'1.2k'

And rounds up in the case below:

human_format(1295)
'1.3k'

The rounding happens due to the flag g in string format and I don't know how to tune it. How can I avoid rounding up, keeping everything else the same?

Maurice Meyer :

You can use decimal to round the inital num value:

from decimal import *

def human_format(num):
    # set decimal default options!
    getcontext().prec = 1
    getcontext().rounding = ROUND_DOWN

    _num = Decimal(num)
    num = float(f'{_num:.3g}')
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    num = int(num * 10) / 10
    return f"{f'{num:f}'.rstrip('0').rstrip('.')}{['', 'k', 'M', 'B', 'T'][magnitude]}"


for x in range(1293, 1301):
    print('%s >> %s' % (x, human_format(x)))

Output:

1293 >> 1.2k
1294 >> 1.2k
1295 >> 1.2k
1296 >> 1.2k
1297 >> 1.2k
1298 >> 1.2k
1299 >> 1.2k
1300 >> 1.3k

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19476&siteId=1