DEV Community

Cover image for Representing large numbers in python: the underscore separator
Chidambaram Manivannan
Chidambaram Manivannan

Posted on Originally published at Medium

Representing large numbers in python: the underscore separator

Recently, I learnt a simple way of representing large numbers in python. Say, I had a large number like 8736570164

I had to manually (and erratically) point my finger at the monitor on that number - look for tens, thousands, millions, etc., draw imaginary commas and come to a conclusion, as taught in school. If we cleverly had to include the commas in the number itself, python treats them as items of a tuple, separated by those commas.

num = 8,736,570,164 # -> num = (8, 736, 570, 164)
Enter fullscreen mode Exit fullscreen mode
# Print an awesome loop from 0 to 12345
for i in range(12,346):
  print(i) # -> Oops! It prints from 12 to 345
Enter fullscreen mode Exit fullscreen mode

So, what is the way then? Turns out, python (since version 3.6) provides the underscore character for digit separation, making it easier for human reading.

1_234_567_890 == 1234567890 # -> True
# Both are the number 1,234,567,890
Enter fullscreen mode Exit fullscreen mode

So now, we can print our loop correctly, like:

# So now, I can print it better
for i in range(12_346):
  print(i) # -> Voila! It prints from 0 to 12345
Enter fullscreen mode Exit fullscreen mode

Now let us see some basic rules for this digit separator in numeric literals.

  • A number cannot start or end with an underscore.
num = _314 # -> Error! Well, it creates a variable identifier, not a numeric literal
num = 314_ # -> Error! 
Enter fullscreen mode Exit fullscreen mode
  • There cannot be multiple underscore separators next to each other.
12__345 # -> Error!
Enter fullscreen mode Exit fullscreen mode
  • Underscore separators can also be used for floats. But, there cannot be an underscore separator right next to the decimal point.
num = 3_.141592 # -> Error 
num = 3._141592 # -> Also an error 

num = 3.141_592 # -> Correct!
Enter fullscreen mode Exit fullscreen mode

One last point: let us learn how to output an underscore separated number, given a normal one. We just have to convert it to a formatted string. Python adds in the separators based on the 'International Number System' (thousands, million, billion, etc.,).

num = 1234567890
print(f'{num:_}') # -> 1_234_567_890
Enter fullscreen mode Exit fullscreen mode

When you ask AI to write your code, it typically always writes plain numeric literals like 1234567890.
If you want the AI to write how we humans want to read easily, specify in the prompt to "Format large numbers with underscore digit separators."

Code is read far more often than it is written, so save yourself (and your teammates) the headache of counting digits. Happy coding!

Top comments (0)