python long numbers as string 1

python long numbers as string

import math

def human_format(number):
    units = ['', 'K', 'M', 'G', 'T', 'P']
    k = 1000.0
    magnitude = int(math.floor(math.log(abs(number), k)))
    return f"{number/k**magnitude:.2f}{units[magnitude]}"

Here is what the above code is Doing:
1. We define a list of units, starting with the empty string.
2. We define a constant k, which is 1000.
3. We calculate the magnitude of the number by taking the log base k of the number.
4. We return the number divided by k to the power of the magnitude, with two decimal places.
5. We add the unit at the magnitude index to the end of the string.

Similar Posts