ambigus9
ambigus9

Reputation: 1569

Convert currency string to float with COP cents

I'm trying to convert: "121.231.232,99" into currency format "121231232.99" any suggestion?

The following code works really well with almost use cases that I found:

values = ["2,000,000.00","1,500.00","10,000,000.00","12,123.00","121,231,232.00","121.231.232,99"]

def parse_money_v2(valor):
    import locale
    locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
    value = locale.atof(value)
    value = round(value,2)
    value = "{:.2f}".format(value)
    return value

Thanks

Upvotes: 0

Views: 250

Answers (1)

Cardstdani
Cardstdani

Reputation: 5223

You can use price_parser module as follows:

from price_parser import Price
values = ["2,000,000.00", "1,500.00", "10,000,000.00", "12,123.00", "121,231,232.00", "121.231.232,99"]


def parse_money_v2(valor):
    return Price.fromstring(valor).amount


for i in values:
    print(parse_money_v2(i))

Output:

2000000.00
1500.00
10000000.00
12123.00
121231232.00
121231232.99

Also, try to write all the variable names in the same language, it's a good practice and improves the readability of your code if it's long and will be read by other people.

Upvotes: 2

Related Questions