Wednesday, January 21, 2009

[vb6] Convert formatted string into numeric

The function below is used to convert formatted string that produced by Format() function into numeric value (Double datatype). This function will remove all non-numeric string except minus and decimal delimiter.

Create new module and paste the source below inside your module file (.bas).
  '****************************************************************************
' Name : StrToNumeric
' Author : Chandra Gunawan
' Date : 22-Jan-2009
' Description : Convert formatted string into numeric
'****************************************************************************
Public Function StrToNumeric( _
ByVal pString As String, _
Optional ByVal pDecimalDelimiter As String) As Double

Dim I%, J%, strVal$

If pDecimalDelimiter <> "." And pDecimalDelimiter <> "," Then
pDecimalDelimiter = Trim(Format(0, "#.#"))
End If

'Remove all non-numeric except dot and comma
For I = 1 To Len(pString)
If InStr(1, "-0123456789" & pDecimalDelimiter, Mid(pString, I, 1)) > 0 Then
strVal = strVal & Mid(pString, I, 1)
End If
Next

'Remove unused delimiter
J = Len(strVal) - Len(Replace(strVal, pDecimalDelimiter, ""))
If J > 1 Then
strVal = Replace(strVal, pDecimalDelimiter, "", 1, J - 1)
End If

'Replace to proper decimal delimiter
If strVal = "" Or strVal = "." Then strVal = "0"
StrToNumeric = CDbl(Replace(strVal, pDecimalDelimiter, "."))
End Function 'StrToNumeric

No comments:

Post a Comment