SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2006
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Extract first numeric string

    Hi all:
    I new here and also new to javascript so I hope you'll be patient if I ask dumb questions. I have a text box with a static value of $2.99 and I want to extract just the 2.99 value and multiply it by a quantity to get a total. While I was searching for something completely different the other day I came across function(I think) which it said would extract the first numeric string in a string including decimal places if there were any. The example it gave was if you had a string of "a62.99retail" it would extract "62.99". The thing is I can't remember what the function was called or where I found it, if anyone could tell me what this function is or a similar one it would greatly appreciated.

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did this quickly but I think it works ok. Using a RegEx might be better - not sure.
    Code:
    function extractFloat(s)
    {
      var c, i = 0, v = 0;
      do {
        c = s.charAt(i++);
      } while (i < s.length && ((c < '0' || c > '9') && c != '.'));
      if (i < s.length) {
        v = parseFloat(s.substr(i-1));
      }
      return v;
    }

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    alert("a62.99retail".match(/\d+(\.\d+)?/)[0])

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Aha! Thanks stereofrog!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •