How to Format currency in python

Formatting currency is important in any programming language especially when we want to present number figures to end users. Knowing how to represent readable numbers to end-users or properly witting numbers while coding can improve readability.

Though there are many third-party packages for formatting currency in python, In most case you will only need to use existing means in the python standard library, I will start by showing you how to best present number figure while coding and then I will show you how to properly add comma separator and the fixed decimal points to any number in python using the format method provided by the string class.

Properly displaying number while coding:

Have you ever got into a situation where you wanted to write the number which consist of a lot of digits and then it become harder for you to read the number mostly because it consists of a lot of digits and you have to count them yourself to figure out what its?

Example bellow:

a = 1000000

 

Well there is always a good news, python now support adding separator while coding. You can use the underscore (“_”) as a comma separator and still your presented value will be counted as a number but will be more readable. But will it be printed the same way to users? Well not , and that is where the python string format method come into play.

Example bellow:

a = 1000_000 

as we can see that "a" variable is still valid, If u didnt know you can actually write that and have python still executing. but that is only in code if you try to execute that code in python shell the underscore will not be displayed and thus endusers will still struggle to understand the presented value.

Let format the "a" value using string format method to have it display a coma separated value along with 2 decimal places.

b = "{:,.2f}".format(a)

The above statement assigns the formatted value of a into a string variable "b", "b" is now very readable to endusers. infact "b" when printed will display the following.

print(b)

1,000,000.00

 

Conclussion:


So this is a python format currency technique you should know. You might be tempted to use third party library for this task, but before jumping to that library make sure it does something which is not already on the python standard library.

Please don’t forget to like , subscribe and follow our social media accounts.

Twitter , Instagram , Youtube and  Facebook @bongobinary.

Do you know any other  technique for using python to format currency that could be better than this? please Give us your feedback on the comment section bellow or share with us on social media by tagging us @bongobinary