Last active
June 24, 2019 12:41
-
-
Save angeloped/8e0a02671ad16f3180d2f56f99867691 to your computer and use it in GitHub Desktop.
A currency formatter written in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# all num is converted into float | |
def currency_format(num): | |
sol = str(float(num)).split(".") | |
sol[0] = sol[0][::-1] | |
final = "" | |
while len(sol[0]): | |
sol_r_e = sol[0][:3]#slice (get 3 characters) | |
sol[0] = sol[0][3:]#slice (decrease) | |
if len(sol_r_e) == 3 and not len(sol[0]) == 0:sol_r_e += "," | |
final += sol_r_e | |
return "P {0}.{1}".format(final[::-1], sol[1]) | |
def currency_unformat(cur): | |
price=cur.split() | |
if len(price) == 2: | |
return price[1].replace(",","") | |
elif len(price) == 1: | |
return price[0].replace(",","") | |
else: | |
return "" | |
print(currency_format(1234.20)) | |
print(currency_unformat(currency_format(1234.20))) | |
''' | |
outputs: | |
>> $ 1,234.2 | |
>> 1234.2 | |
The reason for doing this is that I couldn't find any solution online, that's working on python verson 2.6 and below. | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment