SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: Extract first numeric string
-
Nov 1, 2006, 12:18 #1
- 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.
-
Nov 2, 2006, 09:37 #2
- 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; }
Cross-Browser.com, Home of the X Library
-
Nov 2, 2006, 10:03 #3
- 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])
-
Nov 2, 2006, 10:24 #4
- Join Date
- Dec 2002
- Location
- Alabama, USA
- Posts
- 2,560
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Aha! Thanks stereofrog!
Cross-Browser.com, Home of the X Library
Bookmarks