2

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.