-2

I am trying to write an idle game in pygame (with Python 3.8), but it involves putting some pretty large numbers in some small spaces (150x50 pixels). So, I was looking for an answer to my problem by playing other idle games. I noticed that for most idle games, after the number hits a million, the counter only shows the first 1, 2, or 3 digits (depending on how many are in front of the comma). For example, the number 32,532,345 would be shown as 32M and the number 123,423,643,426 would be 123B. So, that led me to ask, is there a Python function that does that? How can I write a python function that would return such a number so that it is only 4 digits long, but represents a much larger quantity? As always, thank you in advance.

CheetSheatOverlode
  • 121
  • 1
  • 1
  • 11

1 Answers1

2

It all depends on the rounding you want to put in place but a simple and generic approach using Python slicing can be the following:

def shorten_number(number_to_shorten):
    str_number_to_shorten = str(number_to_shorten)
    if len(str_number_to_shorten) > 9 and len(str_number_to_shorten) <= 12:
        return str_number_to_shorten[:-9] + "B"
    elif len(str_number_to_shorten) >= 7 and len(str_number_to_shorten) <= 9:
        return str_number_to_shorten[:-6] + "M"

print(shorten_number(32532345))
print(shorten_number(123423643426))

Output
32M
123B

You can extend it and adapt it adding other elif conditions.

Pitto
  • 8,229
  • 3
  • 42
  • 51