#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2006
    Posts
    326
    Rep Power
    9

    Convert string to float?


    Hello, I have a simple question.

    I have a string like '$29.99' and I would like to convert it to a float so that's only 29.99. I would prefer doing this without having to manually remove the $ since it may not be a $ all the time. Is there a parsing function for doing this? Thanks.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2008
    Location
    Estonia
    Posts
    16
    Rep Power
    0
    I'm not sure what you are exactly thinking, but following function should help you somehow.

    python Code:
    def moneyStrToFloat(moneyString):
        if len(moneyString) > 0:
            if moneyString[0] in ['$', '']:
                return float(moneyString[1:])
            else:
                return float(moneyString)
        else:
            raise Exception('Empty string')
  4. #3
  5. Paris est magique!
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2004
    Location
    France!
    Posts
    370
    Rep Power
    96
    What about:

    Code:
      
          def moneyStrToFloat(moneyString):
              return float(moneyString.replace('$','').replace('',''))
    It throws the exception you need:
    - ValueError: empty string for float()
    - ValueError: invalid literal for float(): xxxxx
    etc.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    430
    Rep Power
    67
    Or even:

    Python Code:
    import re
    float_pat = re.compile('[0-9]+(\.[0-9]+)?')
    if re.search(float_pat, s) is not None:
        # Do something


    This would grab the first substring that resembles a float from the string s and do something with it.

IMN logo majestic logo threadwatch logo seochat tools logo