B4J Code Snippet String Contains a Valid Number

SubName: ValidNumber

Description: A multi purpose number validator

B4X:
Private Sub ValidNumber(Str As String, Negative As Boolean, Decimal As Boolean) As Boolean
    If Str = "" Then Return False
    Dim RegexStr As StringBuilder
    RegexStr.Initialize
    If Negative Then RegexStr.Append("-?")
    If Decimal Then
        RegexStr.Append("[0-9]*\.[0-9]*|")
        If Negative Then RegexStr.Append("-?")
    End If
    RegexStr.Append("[0-9]*")
    Return Regex.IsMatch(RegexStr.ToString,Str)

    'Complete Regex String for all tests "-?[0-9]*\.[0-9]*|-?[0-9]*"
End Sub


Dependencies: None

Tags: Number Validator

The attached project for B4j shows the use I wrote it for with error reporting.
This requires CSSUtils.
 

Attachments

  • ValidNumber.zip
    2.5 KB · Views: 404
Last edited:

LucaMs

Expert
Licensed User
Longtime User
Can this be useful (... and is it possible to optimize it?)?
It's your function (changed name) without Negative and Decimal parameters.

B4X:
Private Sub IsValidNumber(Str As String) As Boolean
    If Str = "" Then Return False
 
    Dim Negative As Boolean, Decimal As Boolean
 
    Negative = Str.Trim.StartsWith("-")
 
    ' Decimal?
    Dim Matcher1 As Matcher
    Matcher1 = Regex.Matcher("\.", Str)
    Dim DecimalCount As Int = 0
    Do While Matcher1.Find
        DecimalCount = DecimalCount + 1
    Loop
    Decimal = (DecimalCount = 1)
 
    Dim RegexStr As StringBuilder
    RegexStr.Initialize
    If Negative Then RegexStr.Append("-?")
    If Decimal Then
        RegexStr.Append("[0-9]*\.[0-9]*|")
        If Negative Then RegexStr.Append("-?")
    End If
    RegexStr.Append("[0-9]*")
    Return Regex.IsMatch(RegexStr.ToString,Str)

    'Complete Regex String for all tests "-?[0-9]*\.[0-9]*|-?[0-9]*"
End Sub
 

Harris

Expert
Licensed User
Longtime User
Also - Valid Number: neg or dec...

B4X:
If IsNumber("-12345.567") Then
        Log(" string as number was valid")
    Else
        Log(" string as number was NOT valid")
    End If
 

giannimaione

Well-Known Member
Licensed User
Longtime User
B4X:
If IsNumber("8d") Then
        Log(" strange!")
    Else
        Log(" string as number was NOT valid")
    End If
 

Harris

Expert
Licensed User
Longtime User
IsNumber("8d")

Strange indeed!

Seems ( d, D, f, F, ) when found in string (1 time only - upper or lower case - following any valid digits)...

IsNumber("1d") , "2322d", "3333343F" all return as valid numbers -true

IsNumber("1d2") , "2d3d", "3F4" , "d1" ,"d15f" all return as NOT valid numbers -false

There must be a reason for this erroneous behaviour... (d and f as valid number - but only when above condition is met)

B4X:
Program started.
 
 string as number 1a: false
 string as number 1b: false
 string as number 1c: false
 string as number 1d: true
 string as number 1e: false
 string as number 1f: true
 string as number 1g: false
 string as number 1h: false
 string as number 1i: false
 string as number 1j: false
 string as number 1k: false
 string as number 1l: false
 string as number 1m: false
 string as number 1n: false
 string as number 1o: false
 string as number 1p: false
 string as number 1q: false
 string as number 1r: false
 string as number 1s: false
 string as number 1t: false
 string as number 1u: false
 string as number 1v: false
 string as number 1w: false
 string as number 1x: false
 string as number 1y: false
 string as number 1z: false
 

OliverA

Expert
Licensed User
Longtime User
d or D = double
f or F = float
Helps with assignments to tell the compiler it is not an int.
 

Harris

Expert
Licensed User
Longtime User
d or D = double
f or F = float
Helps with assignments to tell the compiler it is not an int.
Ok, makes sense in that regard - but in the context of IsNumber ( string ) - where "d" should be evaluated as a string (char) - not a type (int, float, double)?
 

OliverA

Expert
Licensed User
Longtime User
The help for IsNumber says: "Tests whether the specified string can be safely parsed as a number." This parsing is for the underlying language, not a routine you would write. Since the underlying language understands the d and f, it's a valid part of a string representation of a number (for this case, seeing if the underlying language can safely parse the string as a number). I guess it's more of a CanMyLanguageTakeThisStringAndSeeItAsANumberICanAssignToMyLanguagesPrimitiveDataTypesForNumbers. IsNumber is just shorter.
 

Harris

Expert
Licensed User
Longtime User
The help for IsNumber says: "Tests whether the specified string can be safely parsed as a number." This parsing is for the underlying language, not a routine you would write. Since the underlying language understands the d and f, it's a valid part of a string representation of a number (for this case, seeing if the underlying language can safely parse the string as a number). I guess it's more of a CanMyLanguageTakeThisStringAndSeeItAsANumberICanAssignToMyLanguagesPrimitiveDataTypesForNumbers. IsNumber is just shorter.
Whew! That's a mouthful...
Great explanation!
I guess the key word is "safely" - and what you expect using the function.

B4X:
Dim nn As String = "8d"
    Dim res As Double
    
    If IsNumber(nn) Then
        res = nn * 1.5
    End If
    Log(" Result: "&res)  ' safely returns  12

I guess it is "safe". Now I know (unless shown otherwise).

Thanks
 
Top