Monkey Raptor

Wednesday, March 16, 2016

Python: Formatting Large Integer

Hello again. Hehe.

This is an equivalency method in Python of earlier JavaScript post about Formatting Large Integer. It has demos of the method (in JavaScript).

So before we start, the number format in any application, usually, needs to be readable (for interface, such as the dilly we look at) and process-able -- the original format for calculation and then it will be displayed on the dilly we look at.

This is a method to make a large integer readable, of some sort. In another words, this is a Python snippet to insert separators between digits.

There are countries which use comma as large digit separator and point as decimal mark, and there are countries that use the opposite of that.

The first concept, for example:

  • 1,000,400 (large integer) -- it's one million and four hundred
  • 23.58 (decimal) -- twenty three point fifty eight
  • 1,000,000.253 (seriously) -- one million point two hundred and fifty three

And the second one:

  • 1.000.400 (large integer) -- one million and four hundred
  • 23,58 (decimal) -- twenty three comma fifty eight
  • 1.000.000,253 (yeah that) -- one million and stuff

Why they differ? It's history department, long story long, it had something to do with the ancient Roman.

Anyway, the snippet below only focuses on the first one of all, the large integer.
To format an integer larger than 999 to be like either of those -- positive and negative (smaller than -999).

Here it goes:

This function is equipped with two filters at the beginning. If either one (a or b) is invalid, it won't do any "formatting", just return the original value.

The concept is the exact same as the earlier JavaScript post, and it's translated to Python.

These are the outputs on my Python interpreter:

The output of this is a string type.


This "helper" function can be expanded to accommodate floating number and such, plus adding the head and tail. Like, $1,000.00 or $1,000.- and so on. Depends on your data structure.

And then, to revert it back to number, we can strip either the comma or point or any other string (using replace), and convert it to integer (or float/long).


That's the glimpse of it. See you again.

Python: Formatting Large Integer
https://monkeyraptor.johanpaul.net/2016/03/python-formatting-large-integer.html?m=0

No comments

Post a Comment

Tell me what you think...