| Answer: |
If you are sure your string is a well-formed text number (i.e. it's not 123xyz456 or something that doesn't really represent the value you want) then you can simply clean the offending characters and spaces from it with a regular expression.
In VBScript:
Function StripNonNum(strInput) Dim regEx ' Create a regular expression Set regEx = New RegExp
' Match any character NOT in this list regEx.Pattern = "[^0123456789\.]" regEx.IgnoreCase = True regEx.Global = True
' Replace matches with zero length string StripNonNum = regEx.Replace(strInput, "") End Function
' Returns: 51234.98 Response.Write StripNonNum("$51, 234.98")
|
Or in JScript:
<%@language=JScript%> <%
// Acts exactly the same as the VBScript version function MakeNumber(strInput) { var re = new RegExp('[^1234567890\.]', 'gi') return(strInput.replace(re, '')); }
// Returns 51234.98 Response.Write(MakeNumber('$51, 234.98')); %>
|
For more information on regular expressions be sure to check out the Regular Expression Article Index! Happy Programming!
Addendum by Bill Wilkinson (10/16/2000 6:30:00 PM)
|
VBScript actually has a built-in function that will do this work for you. Further, it is "localized," meaning that if you use it in the USA it will recognize the dollar sign as a currency symbol but in Japan it will recognize the yen sign, etc.
The function is CCur, meaning "Convert CURrency."
Some examples:
Response.Write CCur("$51,234.98") ' will write 51234.98 Response.Write CCur("4.55555") ' will write 4.5556
|
Note that currency is always represented internally by MS with four digits to the right of the decimal point, hence the rouding on that second example.
A sneaky way to use CCur and, at the same time, check for errors might go something like this:
<% val = "NOT VALID" On Error Resume Next val = CCur( Request("money") ) On Error Goto 0 Response.Write val %>
|
If you happen to want to process Deutshce Marks (money in Germany), you could just add
and now $12,345.67 will be rejected but 123.456,78 DM will be accepted! Can be quite handy for sites that need to handle several different national currencies.
|