2

I've looked through the 'currency' threads, but they're all for going the other way. I'm reading financial data that comes in as $1,234.56 &c, with everything a string. I split the input line, and want to convert the value item to float for add/subtract (I'm mot worried about roundoff error). Naturally, the float() throws an error.

I could write a function to call as 'amount = float(num(value_string)), but woder if there's a "dollar_string_to_float()" function in one of the 32,000 Python modules.

David Greydanus
  • 2,551
  • 1
  • 23
  • 42
ZZMike
  • 540
  • 2
  • 5
  • 8
  • 1
    Take a look here http://stackoverflow.com/questions/8421922/how-do-i-convert-a-currency-string-to-a-floating-point-number-in-python – FBidu May 30 '15 at 00:04

2 Answers2

1

Look into the regular expressions module. You can compile a pattern that matches your dollars/cents format and extract the floating-point number from it.

Johnas Cukier
  • 670
  • 1
  • 7
  • 11
1

I think this question is slightly different from this question, but I'm not sure.

Anyway, the code from the afformentioned question just need one function change from Decimal to Float and the removal of the Decimal import.

As you requested, the code is in a dollar_string_to_float function:

>>> from re import sub

>>> def dollar_string_to_float(s):
        return float(sub(r'[^\d.]', '', money))


>>> money = '$1,234.56'
>>> print dollar_string_to_float(money)
1234.56
Community
  • 1
  • 1
David Greydanus
  • 2,551
  • 1
  • 23
  • 42