Pretty numbers in Python
In coding, large numbers are not pretty, and it's hard to interpret them. It's fine until you don't need to show them to the user, because you can count the number of digits if needed, but you don't want that experience for the user.
Let's explore the options for making the output numbers more readable and easier to work with.
The user experience
Look at this:
15315633662
That is fifteen billion, three hundred fifteen million, six hundred thirty-three thousand, six hundred sixty-two. (Thank you ChatGPT)
To make it easier to read, here are some separators added: 15,315,633,662
But that is still a "hard to read" number. At this scale, the last few digits are probably not that relevant to many users. That's why we usually see numbers like:
15.32 billion
15.3B
15,316 million
Depending on how we want to communicate and round our number, all the above can present the same long value we have.
To achieve an output like the above, you can use Babel.
It is a Python library that assists in internationalizing and localizing applications.
To format numbers, you can use the format_compact_decimal
method:
That looks way better now.
Your experience
To make formatting even more confusing, here are two numbers that can mean the same thing:
1,099.98
1.099,98
Note the commas and dots. The first is a US standard. It uses a comma for thousands and a dot for decimals. But in the EU, it is usually the other way around. For example, in Germany, they use a dot for thousands and a comma for decimals.
You can use Babel to resolve this confusion:
parse_decimal('1,099.98', locale='en_US')
→ converts it to1099.98
as a float.parse_decimal('1.099,98', locale='de')
→ also converts to1099.98
, respecting the German format.
Now, imagine a situation when you need to work with files that are coming in from two different standards. Date formatting, currency formatting, and time zones... Pain in the neck for sure.
Babel has some sort of solution to all the above scenarios.
I was working on a project that required pretty number outputs, and my research led to Babel. Easy solution, would recommend.