Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a currency string to a floating point number in Python?

I have some strings representing numbers with specific currency format, for example:

money="$6,150,593.22" 

I want to convert this string into the number

6150593.22 

What is the best way to achieve this?

like image 445
Javier Novoa C. Avatar asked Dec 07 '11 20:12

Javier Novoa C.


People also ask

How do you convert a string or number to a floating point number in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you convert a string to a floating point number?

The atof() function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

How do you convert data to float in Python?

To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.


1 Answers

Try this:

from re import sub from decimal import Decimal  money = '$6,150,593.22' value = Decimal(sub(r'[^\d.]', '', money)) 

This has some advantages since it uses Decimal instead of float (which is better for representing currency) and it also avoids any locale issues by not hard-coding a specific currency symbol.

like image 102
Andrew Hare Avatar answered Oct 04 '22 13:10

Andrew Hare