isNumber: find out if a string variable contains (only) a numeric value
-
"isNumber" by @Discostew
Share Code : N1ECBNNDNN// function: isNumber // description: find out if a string variable contains (only) a numeric value // author : @Discostew // arguments : // variable: string to be tested // returns : // 0 : not a numeric value // 1 : a float // 2 : an integer function isNumber( variable ) int result = false if ( len( variable ) > 0 ) then if ( ( len ( variable ) > 1 ) and ( variable[ 0 ] == "-" ) ) then variable = "1" + variable[ 1: ] else variable = "1" + variable endIf int cut = len( str( int( variable ) ) ) variable = variable[ cut: ] if ( len( variable ) > 0 ) then if ( ( len ( variable ) > 1 ) and ( variable[ 0 ] == "." ) ) then cut = len( str( int( "1" + variable[ 1: ] ) ) ) variable = variable[ cut: ] result = len (variable ) == 0 endIf else result = 2 endIf endIf return result // Unit test code by @PB____ // print with new line function printLn( value ) print( value, "\n" ) return void // join a series of values together in a string function join(values) string result = "" int i for i = 0 to len( values ) loop result += str( values[ i ] ) repeat return result // assert that value1 is equal to value2 function assertEqual( value1, value2 ) string str1 = str( value1 ) string str2 = str( value2 ) string outcome = "" if str1 == str2 then ink( lime ) outcome = "success" else ink( red ) outcome = "fail" endif println( join( [ "assert ", str1, " equals to ", str2, ": ", outcome ] ) ) return void // print test description function description( text ) ink( { 0.5, 0.5, 0.5, 1 } ) println(text) return void // run unit tests with the specified delay at the end function runUnitTests( duration ) description( "test integer" ) string stringVar = "12345" int output = isNumber( stringVar ) assertEqual( output, 2 ) description( "test float" ) string stringVar = "3.1415926" int output = isNumber( stringVar ) assertEqual( output, 1 ) description( "test negative" ) string stringVar = "-10" int output = isNumber(stringVar) assertEqual( output, 2 ) description( "test text" ) string stringVar = "the quick brown fox" int output = isNumber( stringVar ) assertEqual( output, 0 ) description( "test mixed" ) string stringVar = "10x589.0" int output = isNumber( stringVar ) assertEqual( output, 0 ) description( "test float with no integer part" ) string stringVar = ".5" int output = isNumber( stringVar ) assertEqual( output, 1 ) update() sleep( duration ) return void runUnitTests( 10 )
-
@pianofire Thanks for sharing this this might be very usefull