Determine if a string is numeric: Difference between revisions
Content deleted Content added
Updated D entry |
|||
Line 814: | Line 814: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<lang lb> |
<lang lb> |
||
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0" |
|||
'Returns 1 if string is only numeric otherwise returns 0 |
|||
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end" |
|||
Print isNumericOnlyString("123") |
|||
Print isNumericOnlyString("12a") |
|||
while n$ <> "end" |
|||
Function isNumericOnlyString(string$) |
|||
read n$ |
|||
isNumericOnlyString = str$(Val(string$)) = string$ |
|||
print n$, IsNumber(n$) |
|||
End Function |
|||
wend |
|||
end |
|||
function IsNumber(string$) |
|||
on error goto [NotNumber] |
|||
string$ = trim$(string$) |
|||
'check for float overflow |
|||
n = val(string$) |
|||
'assume it is number and try to prove wrong |
|||
IsNumber = 1 |
|||
for i = 1 to len(string$) |
|||
select case mid$(string$, i, 1) |
|||
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" |
|||
HasNumeric = 1 'to check if there are any digits |
|||
case "e", "E" |
|||
'"e" must not occur more than once |
|||
'must not occur before digits |
|||
if HasE > 0 or HasNumeric = 0 then |
|||
IsNumber = 0 |
|||
exit for |
|||
end if |
|||
HasE = i 'store position of "e" |
|||
HasNumeric = 0 'needs numbers after "e" |
|||
case "-", "+" |
|||
'must be either first character or immediately after "e" |
|||
'(HasE = 0 if no occurrences yet) |
|||
if HasE <> i-1 then |
|||
IsNumber = 0 |
|||
exit for |
|||
end if |
|||
case "." |
|||
'must not have previous points and must not come after "e" |
|||
if HasE <> 0 or HasPoint <> 0 then |
|||
IsNumber = 0 |
|||
exit for |
|||
end if |
|||
HasPoint = 1 |
|||
case else |
|||
'no other characters allowed |
|||
IsNumber = 0 |
|||
exit for |
|||
end select |
|||
next i |
|||
'must have digits |
|||
if HasNumeric = 0 then IsNumber = 0 |
|||
[NotNumber] |
|||
end function |
|||
</lang> |
</lang> |
||