RosettaCodeData/Task/Determine-if-a-string-is-nu.../FreeBASIC/determine-if-a-string-is-nu...

96 lines
2.0 KiB
Plaintext

' FB 1.05.0 Win64
Dim Shared symbols(0 To 15) As UByte
For i As Integer = 48 to 57
symbols(i - 48) = i
Next
For i As Integer = 97 to 102
symbols(i - 87) = i
Next
Const plus As UByte = 43
Const minus As Ubyte = 45
Const dot As UByte = 46
Function isNumeric(s As Const String, base_ As Integer = 10) As Boolean
If s = "" OrElse s = "." OrElse s = "+" OrElse s = "-" Then Return False
Err = 0
If base_ < 2 OrElse base_ > 16 Then
Err = 1000
Return False
End If
Dim t As String = LCase(s)
If (t[0] = plus) OrElse (t[0] = minus) Then
t = Mid(t, 2)
End If
If Left(t, 2) = "&h" Then
If base_ <> 16 Then Return False
t = Mid(t, 3)
End if
If Left(t, 2) = "&o" Then
If base_ <> 8 Then Return False
t = Mid(t, 3)
End if
If Left(t, 2) = "&b" Then
If base_ <> 2 Then Return False
t = Mid(t, 3)
End if
If Len(t) = 0 Then Return False
Dim As Boolean isValid, hasDot = false
For i As Integer = 0 To Len(t) - 1
isValid = False
For j As Integer = 0 To base_ - 1
If t[i] = symbols(j) Then
isValid = True
Exit For
End If
If t[i] = dot Then
If CInt(Not hasDot) AndAlso (base_ = 10) Then
hasDot = True
IsValid = True
Exit For
End If
Return False ' either more than one dot or not base 10
End If
Next j
If Not isValid Then Return False
Next i
Return True
End Function
Dim s As String
s = "1234.056789"
Print s, " (base 10) => "; isNumeric(s)
s = "1234.56"
Print s, " (base 7) => "; isNumeric(s, 7)
s = "021101"
Print s, " (base 2) => "; isNumeric(s, 2)
s = "Dog"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "Bad125"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "-0177"
Print s, " (base 8) => "; isNumeric(s, 8)
s = "+123abcd.ef"
Print s, " (base 16) => "; isNumeric(s, 8)
s = "54321"
Print s, " (base 6) => "; isNumeric(s, 6)
s = "123xyz"
Print s, " (base 10) => "; isNumeric(s)
s = "xyz"
Print s, " (base 10) => "; isNumeric(s)
Print
Print "Press any key to quit"
Sleep