Page 1 of 1

How to test if a variable is an integer?

Posted: Sat Oct 12, 2024 11:02 pm
by Python27au
Question
Is there a command to detect if a variable is a number?

BASIC treats numbers in a string like numbers. I have an array of strings which contain both words and integers. Id like to do something like this

For i = 1 to 10
If ArrayOfValues$(i)=<an integer> then
x=ArrayOfValues(i)
print ArrayOfLabels(x)
Else
Print ArrayOfValues(i)
End if
Next i

Is there an elegant way of determining if ArrayOfValues(i) is an integer?

Re: How to test if a variable is an integer?

Posted: Sun Oct 13, 2024 1:41 pm
by Dutchman
The function 'Numeric' in the following test program culd be used

Code: Select all

'Numbercheck
DIM A$(10)
A$(1)="Number"
A$(2)=" 123.456"
FOR i=1 TO 2
PRINT A$(i);
IF Numeric(A$(i)) THEN
  PRINT " is a number"
  ELSE 
  PRINT " is NOT a number"
ENDIF
NEXT i
END

DEF Numeric(a$)
b=VAL(a$)
IF STR$(b,"")=TRIM$(a$) THEN 
  RETURN 1
  ELSE
  RETURN 0
ENDIF
END DEF
The output is:

Code: Select all

Number is NOT a number
123.456 is a number

Re: How to test if a variable is an integer?

Posted: Mon Oct 14, 2024 2:22 am
by Python27au
Thank you.