
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
For this program, a valid numeric string literal consists of only numbers (ascii $30-$39), up to oneleading minus sign, and no more than one decimal point. Anything else, including the null string, is considered non-numeric.
Macros used (VASM syntax):
macro loadpair,regs,addrlda #<\addrsta \regslda #>\addrsta \regs+1endmmacro pushYtyaphaendmmacro popYplatayendm
The code:
*=$0801db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00 ;required init code on commodore 64 floppy disks*=$0810lda #$0ejsr chrout ;required for my printing routine to work.z_HL equ $02z_L equ $02z_H equ $03z_B equ $04loadpair z_HL,TestString0jsr isStringNumericloadpair z_HL,TestString1jsr isStringNumericloadpair z_HL,TestString2jsr isStringNumericloadpair z_HL,TestString3jsr isStringNumericloadpair z_HL,TestString4jsr isStringNumericloadpair z_HL,TestString5jsr isStringNumericloadpair z_HL,TestString6jsr isStringNumericloadpair z_HL,TestString7jsr isStringNumericloadpair z_HL,TestString8jsr isStringNumericrts;return to basicisStringNumeric:; input: z_HL = source addresspushYldy #0sty z_B;our tally for decimal pointscheckFirstChar:lda (z_HL),ybeq notNumeric;a null string is not a valid number!cmp #'-'beq isNegative_OKcmp #'.'beq isFloat_OKand #$30cmp #$30beq isNumeral_OK;else, is not numericnotNumeric:popYjsr PrintString_TextScreen;prints what's already in z_HLjsr NewLineloadpair z_HL,isStringNumeric_Failjsr PrintString_TextScreenjsr NewLinejmp NewLine;rtsisNegative_OK:isNumeral_OK:inyjmp loop_isStringNumericisFloat_OK:inyinc z_Bloop_isStringNumeric:lda (z_HL),ybeq Terminated_isStringNumericcmp #'.'beq CheckIfDecimalAlreadyOccurredand #$30cmp #$30bne notNumericloop_overhead_isStringNumeric:inyjmp loop_isStringNumericCheckIfDecimalAlreadyOccurred:lda z_Bbne notNumericinc z_Bjmp loop_overhead_isStringNumericTerminated_isStringNumeric:;if we got this far the string is numeric.popYjsr PrintString_TextScreen;prints what's already in z_HLjsr NewLineloadpair z_HL,isStringNumeric_Passjsr PrintString_TextScreenjsr NewLinejmp NewLine;rtsisStringNumeric_Pass:db "IS NUMERIC",0isStringNumeric_Fail:db "IS NOT NUMERIC",0TestString0:db 0TestString1:db "123",0TestString2:db "-30",0TestString3:db "123.45",0TestString4:db "-123.45",0TestString5:db "ABCDE",0TestString6:db "-34-5",0TestString7:db "1.000.000",0TestString8:db ".23456",0
ready.load"*",8,1:searching for *loadingready.runIS NOT NUMERIC123IS NUMERIC-30IS NUMERIC123.45IS NUMERIC-123.45IS NUMERICABCDEIS NOT NUMERIC-34-5IS NOT NUMERIC1.000.000IS NOT NUMERIC.23456IS NUMERICready.
:number?>n>kindns:nn:=;
/* ARM assembly Raspberry PI *//* program strNumber.s *//*******************************************//* Constantes file *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc".equ BUFFERSIZE, 100/* Initialized data */.dataszMessNum: .asciz "Enter number : \n"szMessError: .asciz "String is not a number !!!\n"szMessInteger: .asciz "String is a integer.\n"szMessFloat: .asciz "String is a float.\n"szMessFloatExp: .asciz "String is a float with exposant.\n"szCarriageReturn: .asciz "\n"/* UnInitialized data */.bss sBuffer: .skip BUFFERSIZE/* code section */.text.global main main: loop: ldr x0,qAdrszMessNum bl affichageMess mov x0,#STDIN // Linux input console ldr x1,qAdrsBuffer // buffer address mov x2,#BUFFERSIZE // buffer size mov x8, #READ // request to read datas svc 0 // call system ldr x1,qAdrsBuffer // buffer address mov x2,#0 // end of string sub x0,x0,#1 // replace character 0xA strb w2,[x1,x0] // store byte at the end of input string (x0 contains number of characters) ldr x0,qAdrsBuffer bl controlNumber // call routine cmp x0,#0 bne 1f ldr x0,qAdrszMessError // not a number bl affichageMess b 5f1: cmp x0,#1 bne 2f ldr x0,qAdrszMessInteger // integer bl affichageMess b 5f2: cmp x0,#2 bne 3f ldr x0,qAdrszMessFloat // float bl affichageMess b 5f3: cmp x0,#3 bne 5f ldr x0,qAdrszMessFloatExp // float with exposant bl affichageMess5: b loop100: // standard end of the program mov x0, #0 // return code mov x8, #EXIT // request to exit program svc 0 // perform system callqAdrszMessNum: .quad szMessNumqAdrszMessError: .quad szMessErrorqAdrszMessInteger: .quad szMessIntegerqAdrszMessFloat: .quad szMessFloatqAdrszMessFloatExp: .quad szMessFloatExpqAdrszCarriageReturn: .quad szCarriageReturnqAdrsBuffer: .quad sBuffer/******************************************************************//* control if string is number */ /******************************************************************//* x0 contains the address of the string *//* x0 return 0 if not a number *//* x0 return 1 if integer eq 12345 or -12345 *//* x0 return 2 if float eq 123.45 or 123,45 or -123,45 *//* x0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 */controlNumber: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers mov x1,#0 mov x3,#0 // point counter 1: ldrb w2,[x0,x1] cmp x2,#0 // end string ? beq 7f cmp x2,#' ' // space ? bne 3f add x1,x1,#1 b 1b // loop 3: cmp x2,#'-' // negative ? bne 4f add x1,x1,#1 b 5f4: cmp x2,#'+' // positive ? bne 5f add x1,x1,#15: ldrb w2,[x0,x1] // control space cmp x2,#0 // end ? beq 7f cmp x2,#' ' // space ? bne 6f add x1,x1,#1 b 5b // loop6: ldrb w2,[x0,x1] cmp x2,#0 // end ? beq 14f cmp x2,#'E' // exposant ? beq 9f cmp x2,#'e' // exposant ? beq 9f cmp x2,#'.' // point ? bne 7f add x3,x3,#1 // yes increment counter add x1,x1,#1 b 6b // and loop7: cmp x2,#',' // comma ? bne 8f add x3,x3,#1 // yes increment counter add x1,x1,#1 b 6b // and loop8: cmp x2,#'0' // control digit < 0 blt 99f cmp x2,#'9' // control digit > 0 bgt 99f add x1,x1,#1 // no error loop digit b 6b9: // float with exposant add x1,x1,#1 ldrb w2,[x0,x1] cmp x2,#0 // end ? beq 99f cmp x2,#'-' // negative exposant ? bne 10f add x1,x1,#110: mov x4,#0 // nombre de chiffres 11: ldrb w2,[x0,x1] cmp x2,#0 // end ? beq 13f cmp x2,#'0' // control digit < 0 blt 99f cmp x2,#'9' // control digit > 9 bgt 99f add x1,x1,#1 add x4,x4,#1 // counter digit b 11b // and loop13: cmp x4,#0 // number digit exposant = 0 -> error beq 99f // error cmp x4,#2 // number digit exposant > 2 -> error bgt 99f // error mov x0,#3 // valid float with exposant b 100f14: cmp x3,#0 bne 15f mov x0,#1 // valid integer b 100f15: cmp x3,#1 // number of point or comma = 1 ? blt 100f bgt 99f // error mov x0,#2 // valid float b 100f99: mov x0,#0 // error100: ldp x4,x5,[sp],16 // restaur 2 registres ldp x2,x3,[sp],16 // restaur 2 registres ldp x1,lr,[sp],16 // restaur 2 registres ret /********************************************************//* File Include fonctions *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"
The solution below uses conversion string to number and number to string to determine if the string is numeric.
INCLUDE "D2:REAL.ACT" ;from the Action! Tool KitBYTE FUNC AreEqual(CHAR ARRAY a,b) BYTE i IF a(0)#b(0) THEN RETURN (0) FI FOR i=1 to a(0) DO IF a(i)#b(i) THEN RETURN (0) FI ODRETURN (1)BYTE FUNC IsNumeric(CHAR ARRAY s) CHAR ARRAY tmp(20) INT i CARD c REAL r i=ValI(s) StrI(i,tmp) IF AreEqual(s,tmp) THEN RETURN (1) FI c=ValC(s) StrC(c,tmp) IF AreEqual(s,tmp) THEN RETURN (1) FI ValR(s,r) StrR(r,tmp) IF AreEqual(s,tmp) THEN RETURN (1) FIRETURN (0)PROC Test(CHAR ARRAY s) BYTE res res=IsNumeric(s) Print(s) Print(" is ") IF res=0 THEN Print("not ") FI PrintE("a number.")RETURNPROC Main() Put(125) PutE() ;clear the screen Test("56233") Test("-315") Test("1.36") Test("-5.126") Test("3.7E-05") Test("1.23BC") Test("5.6.3")RETURNThe solution below uses a finite-state machine to determine if a string is numeric.
BYTE FUNC IsSign(CHAR c) IF c='- OR c='+ THEN RETURN (1) FIRETURN (0)BYTE FUNC IsDigit(CHAR c) IF c>='0 AND c<='9 THEN RETURN (1) FIRETURN (0)BYTE FUNC IsDot(CHAR c) IF c='. THEN RETURN (1) FIRETURN (0)BYTE FUNC IsExpSymbol(CHAR c) IF c='E OR c='e THEN RETURN (1) FIRETURN (0)BYTE FUNC IsNumeric(CHAR ARRAY s) DEFINE S_BEGIN="0" DEFINE S_SIGN="1" DEFINE S_BEFORE_DOT="2" DEFINE S_DOT="3" DEFINE S_AFTER_DOT="4" DEFINE S_EXP_SYMBOL="5" DEFINE S_EXP_SIGN="6" DEFINE S_EXP="7" BYTE i,state CHAR c i=1 state=S_BEGIN WHILE i<=s(0) DO c=s(i) IF state=S_BEGIN THEN IF IsSign(c) THEN state=S_SIGN ELSEIF IsDigit(c) THEN state=S_BEFORE_DOT ELSEIF IsDot(c) THEN state=S_DOT ELSE RETURN (0) FI ELSEIF state=S_SIGN THEN IF IsDigit(c) THEN state=S_BEFORE_DOT ELSEIF IsDot(c) THEN state=S_DOT ELSE RETURN (0) FI ELSEIF state=S_BEFORE_DOT THEN IF IsDigit(c) THEN state=S_BEFORE_DOT ELSEIF IsDot(c) THEN state=S_DOT ELSEIF IsExpSymbol(c) THEN state=S_EXP_SYMBOL ELSE RETURN (0) FI ELSEIF state=S_DOT THEN IF IsDigit(c) THEN state=S_AFTER_DOT ELSEIF IsExpSymbol(c) THEN state=S_EXP_SYMBOL ELSE RETURN (0) FI ELSEIF state=S_AFTER_DOT THEN IF IsDigit(c) THEN state=S_AFTER_DOT ELSEIF IsExpSymbol(c) THEN state=S_EXP_SYMBOL ELSE RETURN (0) FI ELSEIF state=S_EXP_SYMBOL THEN IF IsSign(c) THEN state=S_EXP_SIGN ELSEIF IsDigit(c) THEN state=S_EXP ELSE RETURN (0) FI ELSEIF state=S_EXP_SIGN THEN IF IsDigit(c) THEN state=S_EXP ELSE RETURN (0) FI ELSEIF state=S_EXP THEN IF IsDigit(c) THEN state=S_EXP ELSE RETURN (0) FI ELSE RETURN (0) FI i==+1 OD IF state=S_BEGIN OR state=S_DOT OR state=S_EXP_SIGN OR state=S_EXP_SIGN THEN RETURN (0) FIRETURN (1)PROC Test(CHAR ARRAY s) BYTE res res=IsNumeric(s) Print(s) Print(" is ") IF res=0 THEN Print("not ") FI PrintE("a number.")RETURNPROC Main() Test("56233") Test("-315") Test("1.36") Test("-5.126") Test("3.7E-05") Test("1.23BC") Test("5.6.3")RETURNScreenshot from Atari 8-bit computer
56233 is a number.-315 is a number.1.36 is a number.-5.126 is a number.3.7E-05 is a number.1.23BC is not a number.5.6.3 is not a number.
publicfunctionisNumeric(num:String):Boolean{return!isNaN(parseInt(num));}
The first file is the package interface containing the declaration of the Is_Numeric function.
packageNumeric_TestsisfunctionIs_Numeric(Item:inString)returnBoolean;endNumeric_Tests;
The second file is the package body containing the implementation of the Is_Numeric function.
packagebodyNumeric_TestsisfunctionIs_Numeric(Item:inString)returnBooleanisDummy:Float;beginDummy:=Float'Value(Item);returnTrue;exceptionwhenothers=>returnFalse;endIs_Numeric;endNumeric_Tests;
The last file shows how the Is_Numeric function can be called.
withAda.Text_Io;useAda.Text_Io;withNumeric_Tests;useNumeric_Tests;procedureIs_Numeric_TestisS1:String:="152";S2:String:="-3.1415926";S3:String:="Foo123";beginPut_Line(S1&" results in "&Boolean'Image(Is_Numeric(S1)));Put_Line(S2&" results in "&Boolean'Image(Is_Numeric(S2)));Put_Line(S3&" results in "&Boolean'Image(Is_Numeric(S3)));endIs_Numeric_Test;
152 results in TRUE -3.1415926 results in TRUE Foo123 results in FALSE
integeris_numeric(text s){ return !trap_q(alpha, s, 0);}integermain(void){ if (!is_numeric("8192&*")) { o_text("Not numeric.\n"); } if (is_numeric("8192")) { o_text("Numeric.\n"); } return 0;}PROC is numeric = (REF STRING string) BOOL: ( BOOL out := TRUE; PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE); FILE memory; associate(memory, string); on value error(memory, call back false); on logical file end(memory, call back false); UNION (INT, REAL, COMPL) numeric:=0.0; # use a FORMAT pattern instead of a regular expression # getf(memory, ($gl$, numeric)); out);test:( STRING s1 := "152", s2 := "-3.1415926", s3 := "Foo123"; print(( s1, " results in ", is numeric(s1), new line, s2, " results in ", is numeric(s2), new line, s3, " results in ", is numeric(s3), new line )))
152 results in T-3.1415926 results in TFoo123 results in F
begin % determnines whether the string contains an integer, real or imaginary % % number. Returns true if it does, false otherwise % logical procedure isNumeric( string(32) value text ) ; begin logical ok; % the "number" cannot be blank % ok := ( text not = " " ); if ok then begin % there is at least one non-blank character % % must have either an integer or real/immaginary number % % integer: [+|-]digit-sequence % % real: [+|-][digit-sequence].digit-sequence['integer][L] % % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L] % % imaginary: % % [+|-][digit-sequence].digit-sequence['integer][L]I% % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L]I% % The "I" at the end of an imaginary number can appear % % before or after the "L" (which indicates a long number) % % the "I" and "L" can be in either case % procedure nextChar ; charPos := charPos + 1; logical procedure have( string(1) value ch ) ; ( charPos <= maxChar and text(charPos//1) = ch ) ; logical procedure haveDigit ; ( charPos <= maxChar and text(charPos//1) >= "0" and text(charPos//1) <= "9" ) ; integer charPos, maxChar; logical hadDigits, isReal; charPos := 0; maxChar := 31; hadDigits := false; isReal := false; % skip trailing spaces % while maxChar > 0 and text(maxChar//1) = " " do maxChar := maxChar - 1; % skip leading spacesx % while have( " " ) do nextChar; % skip optional sign % if have( "+" ) or have( "-" ) then nextChar; if haveDigit then begin % have a digit sequence % hadDigits := true; while haveDigit do nextChar end if_have_sign ; if have( "." ) then begin % real or imaginary number % nextChar; isReal := true; hadDigits := hadDigits or haveDigit; while haveDigit do nextChar end if_have_point ; % should have had some digits % ok := hadDigits; if ok and have( "'" ) then begin % the number has an exponent % isReal := true; nextChar; % skip optional sign % if have( "+" ) or have( "-" ) then nextChar; % must have a digit sequence % ok := haveDigit; while haveDigit do nextChar; end if_ok_and_have_exponent ; % if it is a real number, there could be L/I suffixes % if ok and isReal then begin integer LCount, ICount; LCount := 0; ICount := 0; while have( "L" ) or have( "l" ) or have( "I" ) or have( "i" ) do begin if have( "L" ) or have( "l" ) then LCount := LCount + 1 else ICount := ICount + 1; nextChar end while_have_L_or_I ; % there can be at most one L and at most 1 I % ok := ( LCount < 2 and ICount < 2 ) end if_ok_and_isReal ; % must now be at the end if the number % ok := ok and charPos >= maxChar end if_ok ; ok end isNumeric ; % test the isNumeric procedure % procedure testIsNumeric( string(32) value n ; logical value expectedResult ) ; begin logical actualResult; actualResult := isNumeric( n ); write( s_w := 0 , """", n, """ is " , if actualResult then "" else "not " , "numeric " , if actualResult = expectedResult then "" else " NOT " , "as expected" ) end testIsNumeric ; testIsNumeric( "", false ); testIsNumeric( "b", false ); testIsNumeric( ".", false ); testIsNumeric( ".'3", false ); testIsNumeric( "3.'", false ); testIsNumeric( "0.0z44", false ); testIsNumeric( "-1IL", false ); testIsNumeric( "4.5'23ILL", false ); write( "---------" ); testIsNumeric( "-1", true ); testIsNumeric( " +.345", true ); testIsNumeric( "4.5'23I", true ); testIsNumeric( "-5'+3i", true ); testIsNumeric( "-5'-3l", true ); testIsNumeric( " -.345LI", true );end.
" " is not numeric as expected"b " is not numeric as expected". " is not numeric as expected".'3 " is not numeric as expected"3.' " is not numeric as expected"0.0z44 " is not numeric as expected"-1IL " is not numeric as expected"4.5'23ILL " is not numeric as expected---------"-1 " is numeric as expected" +.345 " is numeric as expected"4.5'23I " is numeric as expected"-5'+3i " is numeric as expected"-5'-3l " is numeric as expected" -.345LI " is numeric as expected
The isNumeric() method is part of the Apex String Class. Note that it will return false if applied to a decimal, because the '.' character is not a Unicode digit.
String numericString = '123456';String partlyNumericString = '123DMS';String decimalString = '123.456';System.debug(numericString.isNumeric()); // this will be trueSystem.debug(partlyNumericString.isNumeric()); // this will be falseSystem.debug(decimalString.isNumeric()); // this will be falseSystem.debug(decimalString.remove('.').isNumeric()); // this will be true⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123'110
Works with more recent versions ofDyalog APL
⊃⎕VFI'¯'@('-'∘=)'152 -3.1415926 Foo123'⍝ Fast: replacement of - with APL high-minus required for ⎕VFI110⊃⎕VFI'-'⎕R'¯'⊣'152 -3.1415926 Foo123'⍝ Simple: (ditto)110
{∧/⍵∊(⊃,¨'0123456789¯.+')}¨'152''¯3.1415926''Foo123'110
-- isNumString :: String -> BoolonisNumString(s)tryifclassofsisstringthensetctoclassof(sasnumber)cisrealorcisintegerelsefalseendifonerrorfalseendtryendisNumString-- TESTonrunmap(isNumString,{3,3.0,3.5,"3.5","3E8","-3.5","30","three",three,four})--> {false, false, false, true, true, true, true, false, false, false}endrun-- three :: () -> Intscriptthree3endscript-- four :: () -> Intonfour()4endfour-- GENERIC FUNCTIONS FOR TEST-- map :: (a -> b) -> [a] -> [b]onmap(f,xs)tellmReturn(f)setlngtolengthofxssetlstto{}repeatwithifrom1tolngsetendoflsttolambda(itemiofxs,i,xs)endrepeatreturnlstendtellendmap-- Lift 2nd class handler function into 1st class script wrapper-- mReturn :: Handler -> ScriptonmReturn(f)ifclassoffisscriptthenfelsescriptpropertylambda:fendscriptendifendmReturn
{false,false,false,true,true,true,true,false,false,false}
The classic way's slightly simpler, since the coercion resultmust be a real or an integer if the coercion itself didn't error.
onisNumString(s)if(s'sclassis nottext)thenreturnfalsetrysasnumberreturntrueonerrorreturnfalseendtryendisNumString
/* ARM assembly Raspberry PI *//* program strNumber.s *//* Constantes */.equ STDIN, 0 @ Linux input console.equ STDOUT, 1 @ Linux output console.equ EXIT, 1 @ Linux syscall.equ READ, 3 @ Linux syscall.equ WRITE, 4 @ Linux syscall.equ BUFFERSIZE, 100/* Initialized data */.dataszMessNum: .asciz "Enter number : \n"szMessError: .asciz "String is not a number !!!\n"szMessInteger: .asciz "String is a integer.\n"szMessFloat: .asciz "String is a float.\n"szMessFloatExp: .asciz "String is a float with exposant.\n"szCarriageReturn: .asciz "\n"/* UnInitialized data */.bss sBuffer: .skip BUFFERSIZE/* code section */.text.global main main: loop: ldr r0,iAdrszMessNum bl affichageMess mov r0,#STDIN @ Linux input console ldr r1,iAdrsBuffer @ buffer address mov r2,#BUFFERSIZE @ buffer size mov r7, #READ @ request to read datas swi 0 @ call system ldr r1,iAdrsBuffer @ buffer address mov r2,#0 @ end of string sub r0,#1 @ replace character 0xA strb r2,[r1,r0] @ store byte at the end of input string (r0 contains number of characters) ldr r0,iAdrsBuffer bl controlNumber @ call routine cmp r0,#0 bne 1f ldr r0,iAdrszMessError @ not a number bl affichageMess b 5f1: cmp r0,#1 bne 2f ldr r0,iAdrszMessInteger @ integer bl affichageMess b 5f2: cmp r0,#2 bne 3f ldr r0,iAdrszMessFloat @ float bl affichageMess b 5f3: cmp r0,#3 bne 5f ldr r0,iAdrszMessFloatExp @ float with exposant bl affichageMess5: b loop100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc 0 @ perform system calliAdrszMessNum: .int szMessNumiAdrszMessError: .int szMessErroriAdrszMessInteger: .int szMessIntegeriAdrszMessFloat: .int szMessFloatiAdrszMessFloatExp: .int szMessFloatExpiAdrszCarriageReturn: .int szCarriageReturniAdrsBuffer: .int sBuffer/******************************************************************//* control if string is number */ /******************************************************************//* r0 contains the address of the string *//* r0 return 0 if not a number *//* r0 return 1 if integer eq 12345 or -12345 *//* r0 return 2 if float eq 123.45 or 123,45 or -123,45 *//* r0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 */controlNumber: push {r1-r4,lr} @ save registers mov r1,#0 mov r3,#0 @ point counter 1: ldrb r2,[r0,r1] cmp r2,#0 beq 5f cmp r2,#' ' addeq r1,#1 beq 1b cmp r2,#'-' @ negative ? addeq r1,#1 beq 2f cmp r2,#'+' @ positive ? addeq r1,#12: ldrb r2,[r0,r1] @ control space cmp r2,#0 @ end ? beq 5f cmp r2,#' ' addeq r1,#1 beq 2b3: ldrb r2,[r0,r1] cmp r2,#0 @ end ? beq 10f cmp r2,#'E' @ exposant ? beq 6f cmp r2,#'e' @ exposant ? beq 6f cmp r2,#'.' @ point ? addeq r3,#1 @ yes increment counter addeq r1,#1 beq 3b cmp r2,#',' @ comma ? addeq r3,#1 @ yes increment counter addeq r1,#1 beq 3b cmp r2,#'0' @ control digit < 0 blt 5f cmp r2,#'9' @ control digit > 0 bgt 5f add r1,#1 @ no error loop digit b 3b5: @ error detected mov r0,#0 b 100f6: @ float with exposant add r1,#1 ldrb r2,[r0,r1] cmp r2,#0 @ end ? moveq r0,#0 @ error beq 100f cmp r2,#'-' @ negative exposant ? addeq r1,#1 mov r4,#0 @ nombre de chiffres 7: ldrb r2,[r0,r1] cmp r2,#0 @ end ? beq 9f cmp r2,#'0' @ control digit < 0 blt 8f cmp r2,#'9' @ control digit > 0 bgt 8f add r1,#1 add r4,#1 @ counter digit b 7b8: mov r0,#0 b 100f9: cmp r4,#0 @ number digit exposant = 0 -> error moveq r0,#0 @ erreur beq 100f cmp r4,#2 @ number digit exposant > 2 -> error movgt r0,#0 @ error bgt 100f mov r0,#3 @ valid float with exposant b 100f10: cmp r3,#0 moveq r0,#1 @ valid integer beq 100f cmp r3,#1 @ number of point or comma = 1 ? moveq r0,#2 @ valid float movgt r0,#0 @ error100: pop {r1-r4,lr} @ restaur des 2 registres bx lr @ return/******************************************************************//* display text with size calculation */ /******************************************************************//* r0 contains the address of the message */affichageMess: push {r0,r1,r2,r7,lr} @ save registers mov r2,#0 @ counter length */1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call system pop {r0,r1,r2,r7,lr} @ restaur registers bx lr @ returnprintnumeric?"hello world"printnumeric?"1234"printnumeric?"1234 hello world"printnumeric?"12.34"printnumeric?"0x2bf"printnumeric?"!#@$"printnumeric?"-15"
falsetruefalsetruefalsetrue
AutoHotkey has no explicitly defined variable types. A variable containing only digits (with an optional decimal point) is automatically interpreted as a number when a math operation or comparison requires it.
list=0.14-5.2ten0xfLoop,Parse,list,%A_Space%MsgBox,%IsNumeric(A_LoopField)ReturnIsNumeric(x){IfxisnumberReturn,1ElseReturn,0};Output: 1 1 1 0 1
The following function uses the fact that non-numeric strings in AWK are treated as having the value 0 when used in arithmetics, but not in comparison:
$awk'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'
0 1
INPUT "Your string: ", s$IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN PRINT "This is a number"ELSE PRINT "Not a number"ENDIF
user@host $ ./isnumber Your string: 12.3This is a numberuser@host $ ./isnumber Your string: 12E3This is a numberuser@host $ ./isnumber Your string: PINot a numberuser@host $ ./isnumber Your string: HelloNot a number
10INPUT"Enter a string";S$:GOSUB100020IFRTHENPRINT"Is num"ELSEPRINT"Not num"99END1000T1=VAL(S$):T1$=STR$(T1)1010R=T1$=S$ORT1$=" "+S$1099RETURN
#La función isNumeric() es nativa de BASIC256.#Devuelve 1 (verdadero) si la expresión es un entero, #un número de punto flotante o una cadena que se puede#convertir directamente en un número. #De lo contrario, devuelve 0 (falso).#Las siguientes cadenas numéricas son válidas: #“123”, “-345”, “234.234324”, “-34234.123”, “-2.567e7” y “6.7888E-8”. s = "1234.056789"print s, " => "; isNumeric(s)s = "-2.567e7"print s, " => "; isNumeric(s)s = "Dog"print s, " => "; isNumeric(s)s = "Bad125"print s, " => "; isNumeric(s)s = "-0177"print s, " => "; isNumeric(s)s = "0b1110" #binarioprint s, " => "; isNumeric(s)s = "0o177" #octalprint s, " => "; isNumeric(s)s = "0xff" #hexadecimalprint s, " => "; isNumeric(s)end
1234.056789 => 1-2.567e7 => 1Dog => 0Bad125 => 0-0177 => 10b1110 => 10o177 => 10xff => 0
5 print chr$(147);chr$(14)10 input "Enter a string";s$:gosub 1000:print20 if r then print "You entered a number.":goto 9930 print "That is not a number."99 end1000 t1=val(s$):t1$=str$(t1)1010 r=t1$=s$ or t1$=" "+s$1099 return
Enter a string? 15893You entered a number.ready.runEnter a string? LlamasThat is not a number.ready.█
Input "Enter a text or a number: ", v$ 'The "$" establishes that this is a string variable. So whatever entered will be stored as 'a string.If v$ = Str$(Val(v$)) Then 'Str$() converts numeric values to their string counter parts and Val() does the opposite, 'converting strings to their numerical values. By converting the value of whatever is stored 'in v$ to a number and then back to a string it will have either stayed completely the same, 'in which case it is a numeric value (including exponent and hex and oct based numbers) or 'what is returned by the nested Str$() and Val$() functions will be different, in which case 'one, the other, or both returned an error or a truncation of the original string which began 'with numeric characters but was not entirely a number, such as "99, rue de Rivoli". Print "Your entered a number."Else Print "You did not enter a number."End IfSleepSystem
Enter a text or a number: 12345You entered a number.Enter a text or a number: FourYou did not enter a number.Enter a text or a number: 99, rue de RivoliYou did not enter a number.Enter a text or a number: 9E4You entered a number.
NB: While "99, rue de Rivoli" contains a number it is not a number entirely. The Val(v$) in this case would have stopped after it converted the "99" portion of the input, which when converted back to a string and compared to the original input would not result in an equality. 9E4 the program reads as an exponential value.
y = isnumber(s) returns true if s is a number or can be converted to a number.
a=1.2345b="abc"c="-1.2345"printisnumber(a)printisnumber(b)printisnumber(c)
101
set/aa=%arg%+0>nulif%a%== 0(ifnot"%arg%"=="0"(echo Non Numeric.)else(echo Numeric.))else(echo Numeric.)
REPEATREADN$IFFN_isanumber(N$)THENPRINT"'"N$"' is a number"ELSEPRINT"'"N$"' is NOT a number"ENDIFUNTILN$="end"ENDDATA"PI","0123","-0123","12.30","-12.30","123!","0"DATA"0.0",".123","-.123","12E3","12E-3","12+3","end"DEFFN_isanumber(A$)ONERRORLOCAL=FALSEIFEVAL("("+A$+")")<>VAL(A$)THEN=FALSEIFVAL(A$)<>0THEN=TRUEIFLEFT$(A$,1)="0"THEN=TRUE=FALSE
'PI' is NOT a number'0123' is a number'-0123' is a number'12.30' is a number'-12.30' is a number'123!' is NOT a number'0' is a number'0.0' is a number'.123' is a number'-.123' is a number'12E3' is a number'12E-3' is a number'12+3' is NOT a number'end' is NOT a number
~:0\`#v_:"+"-!#v_:"-"-!#v_::"E"-\"e"-*#v_vv_v#<<0<>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_v^$<>>$v>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_>v>^$<>$~:0\`#v_:"+"-#v_vv$_v#<<:#<>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!v0>v^$<v<<<^_^#-"-"<>"ciremuN">:#,_@>>#$_"ciremun toN">:#,_@^<
Although only integer inputs are strictly allowed in Befunge, the code tries to adhere to the floating point conventions in other languages when recognising valid numbers.
'PI' Not numeric'0123' Numeric'-0123' Numeric'12.30' Numeric'-12.30' Numeric'123!' Not numeric'0' Numeric'0.0' Numeric'.123' Numeric'-.123' Numeric'12E3' Numeric'12E-3' Numeric'12+3' Not numeric'end' Not numeric'12..34' Not numeric'12e3.4' Not numeric'192.168.0.1' Not numeric
IsNumeric←1∘•ParseFloat⎊0
To check whether a string is a number, a fraction or an integer, use the patterns#,/ and~/# ("not a fraction and yet a number"). In the pattern matching examples below (which can be typed in at the Bracmat prompt)F denotes 'failure' andS denotes 'success'.
43257349578692:/ F260780243875083/35587980:/ S 247/30:~/# F80000000000:~/# S
The pattern~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#) recognises string representations of floating point numbers.
@("1.000-4E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) F@("1.0004E-54328":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("-464641.0004E-54328":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("1/2.0004E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) F@("1357E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("1357e0":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("13579":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("1.246":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("0.0":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) S@("0.0000":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)) SCalculations with floating point numbers are delegated to UFP (Un-I-fancy-fied Floating Point, because it took me 30 years to dream up a viable way to do FP in Bracmat without breaking existing code) objects. An UFP object compiles and executes code that only handles C "doubles" and (multidimensional) arrays of such values.
ps^^-]to{"Int""Double"}\/~[\/L[1==?*Assumes string is not empty.
Returns true (non-zero) if character-string parameter represents a signed or unsigned floating-point number. Otherwise returns false (zero).
#include<ctype.h>#include<stdbool.h>#include<stdlib.h>boolisNumeric(constchar*s){if(s==NULL||*s=='\0'||isspace(*s)){returnfalse;}char*p;strtod(s,&p);return*p=='\0';}
Framework:.NET 2.0+
publicstaticboolIsNumeric(strings){doubleResult;returndouble.TryParse(s,outResult);// TryParse routines were added in Framework version 2.0.}stringvalue="123";if(IsNumeric(value)){// do something}
Framework:.NET 1.0+
publicstaticboolIsNumeric(strings){try{Double.Parse(s);returntrue;}catch{returnfalse;}}
#include<cctype>#include<cstdlib>boolisNumeric(constchar*s){if(s==nullptr||*s=='\0'||std::isspace(*s)){returnfalse;}char*p;std::strtod(s,&p);return*p=='\0';}
Using stringstream:
#include<sstream> // for istringstreamusingnamespacestd;boolisNumeric(constchar*pszInput,intnNumberBase){istringstreamiss(pszInput);if(nNumberBase==10){doubledTestSink;iss>>dTestSink;}elseif(nNumberBase==8||nNumberBase==16){intnTestSink;iss>>((nNumberBase==8)?oct:hex)>>nTestSink;}elsereturnfalse;// was any input successfully consumed/converted?if(!iss)returnfalse;// was all the input successfully consumed/converted?return(iss.rdbuf()->in_avail()==0);}
Using find:
boolisNumeric(constchar*pszInput,intnNumberBase){stringbase="0123456789ABCDEF";stringinput=pszInput;return(input.find_first_not_of(base.substr(0,nNumberBase))==string::npos);}
Using all_of (requires C++11)
boolisNumeric(conststd::string&input){returnstd::all_of(input.begin(),input.end(),::isdigit);}
ColdFusion Script (CfScript)
isNumeric(42)
(defnnumeric?[s](if-let[s(seqs)](let[s(if(=(firsts)\-)(nexts)s)s(drop-while#(Character/isDigit%)s)s(if(=(firsts)\.)(nexts)s)s(drop-while#(Character/isDigit%)s)](empty?s))))
This works with any sequence of characters, not just Strings, e.g.:
(numeric?[\1\2\3]);; yields logical true
Clojure has a fairly rich set of numeric literals, including Ratios, BigInts and BigDecimals. The Clojure reader will attempt to read any form starting with a digit (optionally preceded by a '+' or '-') as a number. So the following checks to see if such a read is successful:
(require'[clojure.edn:asedn])(import[java.ioPushbackReaderStringReader])(defnnumber-string?[s](boolean(when(and(string?s)(re-matches#"^[+-]?\d.*"s))(let[reader(PushbackReader.(StringReader.s))num(try(edn/readreader)(catchException_nil))](whennum; Check that the string has nothing after the number(=-1(.readreader)))))))
user=>(number-string?"2r101010")trueuser=>(number-string?"22/7")true
COBOL has the intrinsic functionsTEST-NUMVAL andTEST-NUMVAL-C to check if a string is numeric (TEST-NUMVAL-C is used to check if it is also a monetary string). Implementations supporting the 20XX draft standard can also useTEST-NUMVAL-F for floating-point numbers. They return 0 if the string is valid, or the position of the first incorrect character.
program-id.is-numeric.proceduredivision.displayfunctiontest-numval-f("abc")end-displaydisplayfunctiontest-numval-f("-123.01E+3")end-displayiffunctiontest-numval-f("+123.123")equalzerothendisplay"is numeric"end-displayelsedisplay"failed numval-f test"end-displayend-ifgoback.
IDENTIFICATIONDIVISION.PROGRAM-ID.Is-Numeric.DATADIVISION.WORKING-STORAGESECTION.01Numeric-CharsPIC X(10)VALUE"0123456789".01SuccessCONSTANT0.01FailureCONSTANT128.LOCAL-STORAGESECTION.01IPIC 99.01Num-Decimal-PointsPIC 99.01Num-Valid-CharsPIC 99.LINKAGESECTION.01StrPIC X(30).PROCEDUREDIVISIONUSINGStr.IFStr=SPACESMOVEFailureTOReturn-CodeGOBACKEND-IFMOVEFUNCTIONTRIM(Str)TOStrINSPECTStrTALLYINGNum-Decimal-PointsFORALL"."IFNum-Decimal-Points>1MOVEFailureTOReturn-CodeGOBACKELSEADDNum-Decimal-PointsTONum-Valid-CharsEND-IFIFStr(1:1)="-"OR"+"ADD1TONum-Valid-CharsEND-IFPERFORMVARYINGIFROM1BY1UNTILI>10INSPECTStrTALLYINGNum-Valid-CharsFORALLNumeric-Chars(I:1)BEFORESPACEEND-PERFORMINSPECTStrTALLYINGNum-Valid-CharsFORTRAILINGSPACESIFNum-Valid-Chars=FUNCTIONLENGTH(Str)MOVESuccessTOReturn-CodeELSEMOVEFailureTOReturn-CodeEND-IFGOBACK.
The isFinite function is built into JavaScript, so we don't need to create our own function in CoffeeScript.
console.log(isFinite(s)forsin[5,"5","-5","5","5e5",0])# all trueconsole.log(isFinite(s)forsin[NaN,"fred","###"])# all false
Adobe's ColdFusion
<cfsetTestValue=34> TestValue:<cfoutput>#TestValue#</cfoutput><br><cfifisNumeric(TestValue)> is Numeric.<cfelse> is NOT Numeric.</cfif><cfsetTestValue="NAS"> TestValue:<cfoutput>#TestValue#</cfoutput><br><cfifisNumeric(TestValue)> is Numeric.<cfelse> is NOT Numeric.</cfif>
<cfoutput>#isNumeric(42)#</cfoutput>
If the input may be relied upon to not be especially malicious, then it may beread and the result checked for being a number.
(defunnumeric-string-p(string)(let((*read-eval*nil))(ignore-errors(numberp(read-from-stringstring)))))
ignore-errors here handles returning nil in case the input is invalid rather than simply non-numeric.
However,read[-from-string] has the side effect of interning any symbols encountered, and can have memory allocation larger than the input size (due to read syntax such as#*, which takes a length). Theparse-number library provides a numbers-only equivalent ofread.
(defunnumeric-string-p(string)(ignore-errors(parse-number:parse-numberstring))); parse failed, return false (nil)
defnumeric?(s)s.to_frescuefalseend
Using the standard Phobos function (currently binary and hex literals are not recognized):
importstd.stdio,std.string,std.array;voidmain(){foreach(consts;["12"," 12\t","hello12","-12","02","0-12","+12","1.5","1,000","1_000","0x10","0b10101111_11110000_11110000_00110011","-0b10101","0x10.5"])writefln(`isNumeric("%s"): %s`,s,s.strip().isNumeric(true));}
isNumeric("12"): trueisNumeric(" 12 "): trueisNumeric("hello12"): falseisNumeric("-12"): trueisNumeric("02"): trueisNumeric("0-12"): falseisNumeric("+12"): trueisNumeric("1.5"): trueisNumeric("1,000"): trueisNumeric("1_000"): trueisNumeric("0x10"): falseisNumeric("0b10101111_11110000_11110000_00110011"): falseisNumeric("-0b10101"): falseisNumeric("0x10.5"): falseimportstd.stdio,std.string,std.conv,std.array,std.exception;boolisNumeric(instrings)pure{immutables2=s.strip.toLower.replace("_","").replace(",","");try{s2.to!real;}catch(ConvExceptione){if(s2.startsWith("0x"))return!s2[2..$].to!ulong(16).collectException!ConvException;elseif(s2.startsWith("0b"))return!s2[2..$].to!ulong(2).collectException!ConvException;elsereturnfalse;}returntrue;}voidmain(){foreach(immutables;["12"," 12\t","hello12","-12","02","0-12","+12","1.5","1,000","1_000","0x10","0b10101111_11110000_11110000_00110011","-0b10101","0x10.5"])writefln(`isNumeric("%s"): %s`,s,s.isNumeric);}
isNumeric("12"): trueisNumeric(" 12 "): trueisNumeric("hello12"): falseisNumeric("-12"): trueisNumeric("02"): trueisNumeric("0-12"): falseisNumeric("+12"): trueisNumeric("1.5"): trueisNumeric("1,000"): trueisNumeric("1_000"): trueisNumeric("0x10"): trueisNumeric("0b10101111_11110000_11110000_00110011"): trueisNumeric("-0b10101"): falseisNumeric("0x10.5"): falseThis simple function is a wrapper around a built-in Delphi function
functionIsNumericString(constinStr:string):Boolean;vari:extended;beginResult:=TryStrToFloat(inStr,i);end;
This console application tests the function:
programisNumeric;{$APPTYPE CONSOLE}usesClasses,SysUtils;functionIsNumericString(constinStr:string):Boolean;vari:extended;beginResult:=TryStrToFloat(inStr,i);end;{ Test function }vars:string;c:Integer;constMAX_TRIES=10;sPROMPT='Enter a string (or type "quit" to exit):';sIS=' is numeric';sISNOT=' is NOT numeric';beginc:=0;s:='';repeatInc(c);Writeln(sPROMPT);Readln(s);if(s<>'')thenbegintmp.Add(s);ifIsNumericString(s)thenbeginWriteln(s+sIS);endelsebeginWriteln(s+sISNOT);end;Writeln('');end;until(c>=MAX_TRIES)or(LowerCase(s)='quit');end.
Example summarised
123 is numeric-123.456 is numeric-123.-456 is NOT numeric.345 is numericm1k3 is NOT numeric
func String.IsNumeric() { try { parse(this) is Integer or Float } catch _ { false }} var str = "1234567"print(str.IsNumeric())is-numeric s:truetry:drop to-num scatch value-error:notfor v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]:!.( v is-numeric v )
"-3" true "12ef" false "12e3" true "hello" false "3.14" true "0" true "1" true
CREATEORREPLACEFUNCTIONis_valid_number(s)ASCASEWHENsISNULLTHENfalseWHENtry_cast(sASDOUBLE)ISNOTNULLTHENtrueELSEfalseEND;#Illustrationselects,is_valid_number(s)from(selectunnest(['123.0','123.','-123','3.14159','1.2.3','abc','A440',' 12 ','0A','+1E10','1E-10'])ass);
┌─────────┬────────────────────┐│ s │ is_valid_number(s) ││ varchar │ boolean │├─────────┼────────────────────┤│ 123.0 │ true ││ 123. │ true ││ -123 │ true ││ 3.14159 │ true ││ 1.2.3 │ false ││ abc │ false ││ A440 │ false ││ 12 │ true ││ 0A │ false ││ +1E10 │ true ││ 1E-10 │ true │├─────────┴────────────────────┤│ 11 rows 2 columns │└──────────────────────────────┘
def isNumeric(specimen :String) { try { <import:java.lang.makeDouble>.valueOf(specimen) return true } catch _ { return false }}func is_numeric a$ . h = number a$ # because every variable must be used h = h return 1 - error.for s$ in [ "abc" "21a" "1234" "-13" "7.65" ] if is_numeric s$ = 1 print s$ & " is numeric" else print s$ & " is not numeric" ..
abc is not numeric21a is not numeric1234 is numeric-13 is numeric7.65 is numeric
The conversion functionstring->number returns #f - false - in the string is not a number, else returns a number, which is #t - true - as far as logical operations are concerned
(string->number"albert")→#f(string->number-666)→-666(if(string->number666)'YES'NO)→YES
Hg/^([-+]?[0-9]*)(\.[0-9]+([eE][+-]?[0-9]+)?)?$/s//\1\2 is numeric/v/numeric/s/.*/& is not numeric/,pQ
$ cat string-numeric.ed | ed -GlEs string-numeric.input Newline appended56233 is numeric-315 is numeric1.36 is numeric-5.126 is numeric3.7E-05 is numeric1.23BC is not numeric5.6.3 is not numeric
defmoduleRCdodefis_numeric(str)docaseFloat.parse(str)do{_num,""}->true_->falseendendend["123","-12.3","123.",".05","-12e5","+123"," 123","abc","123a","12.3e","1 2"]|>Enum.filter(&RC.is_numeric/1)
["123", "-12.3", "-12e5", "+123"]
(defunstring-valid-number-p(str)"Test if STR is a numeric string.Eliminate strings with commas in them because ELisp numbers donot contain commas. Then check if remaining strings would bevalid ELisp numbers if the quotation marks were removed."(and;; no comma in string, because ELisp numbers do not have commas;; we need to eliminate any string with a comma, because the;; numberp function below will not weed out commas(not(string-match-p","str));; no errors from numberp function testing if a number(ignore-errors(numberp(readstr)))))
Below is ELisp code to test two lists. One is a list of strings that would be acceptable numbers in Emacs ELisp. The second is a list of stringsthat are not valid numbers. The code tests each string in each list.
(setqvalid-strings'("3""0""-0""2.""1000""-4""-5.""6.2""-8.45""+15e2""-15e2""#b101100""#o54""#x2c""1500.0""#24r1k""3"))(setqinvalid-strings'("3cat""1,000""5.6.7""cat3""def""zero"))(with-current-buffer(pop-to-buffer"my-test")(erase-buffer)(insert"Test for valid strings:\n")(dolist(test-stringvalid-strings)(let((test-result))(setqtest-result(string-valid-number-ptest-string))(insert(format"%-8s - %s \n"test-stringtest-result))))(insert"\n""\n")(insert"Test for invalid strings:\n")(dolist(test-stringinvalid-strings)(let((test-result))(setqtest-result(string-valid-number-ptest-string))(insert(format"%-5s - %s \n"test-stringtest-result)))))
Below is the result of the tests:
Test for valid strings:3 - t 0 - t -0 - t 2. - t 1000 - t -4 - t -5. - t 6.2 - t -8.45 - t +15e2 - t -15e2 - t #b101100 - t #o54 - t #x2c - t 1500.0 - t #24r1k - t 3 - t Test for invalid strings:3cat - nil 1,000 - nil 5.6.7 - nil cat3 - nil def - nil zero - nil
fun isNumeric ← logic by text value try ^|So funny: |a) we check if it's castable to a real |b) we obtain the real 0.0 |c) conversion from real to int to get 0 |d) int can be converted to logical to get ⊥ |e) we can negate the result |^ return not when(value.contains("."), logic!int!(real!value * 0), logic!(int!value * 0)) remedy return false endendfun main ← int by List args if args.length æ 1 writeLine(isNumeric(args[0])) else writeLine("value".padEnd(8, " "), " ", "numeric") for each text value in text["0o755", "thursday", "3.14", "0b1010", "-100", "0xff"] writeLine(value.padEnd(8, " "), " ", isNumeric(value)) end end return Runtime.OKendexit main(Runtime.args)value numeric0o755 ⊤thursday ⊥3.14 ⊤0b1010 ⊤-100 ⊤0xff ⊤
Erlang doesn't come with a way to say if a string represents a numeric value or not, but does come with the built-in functionis_number/1, which will return true if the argument passed is either an integer or a float. Erlang also has two functions to transform a string to either a floating number or an integer, which will be used in conjunction withis_number/1.
is_numeric(L)->Float=(catcherlang:list_to_float(L)),Int=(catcherlang:list_to_integer(L)),is_number(Float)orelseis_number(Int).
Short form using predeclared ERRE functions VAL and STR$.
PROGRAM NUMERICPROCEDURE IS_NUMERIC(S$->ANS%)LOCAL T1,T1$ T1=VAL(S$) T1$=STR$(T1) ANS%=(T1$=S$) OR T1$=" "+S$END PROCEDUREBEGIN PRINT(CHR$(12);) INPUT("Enter a string",S$) IS_NUMERIC(S$->ANS%) IF ANS% THEN PRINT("is num") ELSE PRINT("not num")END PROGRAMEnter a string? 12.30is num
include get.efunction is_numeric(sequence s) sequence val val = value(s) return val[1]=GET_SUCCESS and atom(val[2])end function
letis_numerica=fst(System.Double.TryParsea)
:numeric?(string--?)string>number>boolean;
The 'fromStr' methods return a parsed number or given an error. The 'false' tells each method to return null if the string does not parse as a number of given type, otherwise, the 'fromStr' method throws an exception.
classMain{// function to see if str contains a number of any of built-in typesstaticBoolreadNum(Strstr){int:=Int.fromStr(str,10,false)// use base 10if(int!=null)returntruefloat:=Float.fromStr(str,false)if(float!=null)returntruedecimal:=Decimal.fromStr(str,false)if(decimal!=null)returntruereturnfalse}publicstaticVoidmain(){echo("For '2': "+readNum("2"))echo("For '-2': "+readNum("-2"))echo("For '2.5': "+readNum("2.5"))echo("For '2a5': "+readNum("2a5"))echo("For '-2.1e5': "+readNum("-2.1e5"))}}
For '2': trueFor '-2': trueFor '2.5': trueFor '2a5': falseFor '-2.1e5': true
Another example inspired by the Kotlin example. Fantom does not have an enhanced for-loop (foreach) loop, but instead uses Closures as the primary mechanism of iteration.
/* gary chike 08/27/2023 */classMain{staticVoidmain(){inputs:=["152\n","-3.141","Foo123","-0","456bar","1.0E10"]inputs.each|Strinput|{echo("$input.trim \tis "+(isNumeric(input)?"numeric":"not numeric"))}staticBoolisNumeric(Strinput){try{input.toFloatreturntrue}catch(Erre){returnfalse}}}
152 is numeric-3.141 is numericFoo123 is not numeric-0 is numeric456bar is not numeric1.0E10 is numeric
:is-numeric( addr len -- )2dupsnumber??dupif\ not standard, but >number is more cumbersome to use0<if-rottype." as integer =".else2swaptype." as double ="<##s#>typethenelse2dup>floatiftype." as float ="f.elsetype." isn't numeric in base"base@dec.thenthen;s"1234"is-numeric\ 1234 as integer = 1234s"1234."is-numeric\ 1234. as double = 1234s"1234e"is-numeric\ 1234e as float = 1234.s"$1234"is-numeric\ $1234 as integer = 4660 ( hex literal )s"%1010"is-numeric\ %1010 as integer = 10 ( binary literal )s"beef"is-numeric\ beef isn't numeric in base 10hexs"beef"is-numeric\ beef as integer = BEEFs"&1234"is-numeric\ &1234 as integer = 4D2 ( decimal literal )
FUNCTIONis_numeric(string)IMPLICIT NONECHARACTER(len=*),INTENT(IN)::stringLOGICAL::is_numericREAL::xINTEGER::eREAD(string,*,IOSTAT=e)xis_numeric=e==0END FUNCTIONis_numeric
functionisNumeric(constpotentialNumeric:string):boolean;varpotentialInteger:integer;potentialReal:real;integerError:integer;realError:integer;beginintegerError:=0;realError:=0;// system.val attempts to convert numerical value representations.// It accepts all notations as they are accepted by the language,// as well as the '0x' (or '0X') prefix for hexadecimal values.val(potentialNumeric,potentialInteger,integerError);val(potentialNumeric,potentialReal,realError);isNumeric:=(integerError=0)or(realError=0);end;
The following is a more complete and compilable example.
programIsNumeric;typeTDynamicArrayItem=recordStrValue:string;end;varmyDynamicArray:arrayofTDynamicArrayItem;i:Integer;Value:Extended;Code:Integer;begin// Initialize the dynamic array with different data typesSetLength(myDynamicArray,7);myDynamicArray[0].StrValue:='Hello';myDynamicArray[1].StrValue:='42';myDynamicArray[2].StrValue:='3.14159';myDynamicArray[3].StrValue:='World';myDynamicArray[4].StrValue:='99';myDynamicArray[5].StrValue:='0777';// Octal representation for 511myDynamicArray[6].StrValue:='$A1';// Hexadecimal representation for 161// Iterate through the dynamic array and determine data typefori:=Low(myDynamicArray)toHigh(myDynamicArray)dobeginVal(myDynamicArray[i].StrValue,Value,Code);ifCode=0then// The value 0 for Code indicates that the conversion was successful.Writeln('Element ',i,': Numeric Value ',Chr(9),' - ',Value)// Chr(9) = tabelseWriteln('Element ',i,': Non-Numeric Value ',Chr(9),' - ',myDynamicArray[i].StrValue);end;end.{ Val converts the value represented in the string 'StrValue' to a numerical value or an enumerated value, and stores this value in the variable 'Value', which can be of type Longint, Real and Byte or any enumerated type. If the conversion isn't successful, then the parameter 'Code' contains the index of the character in 'StrValue' which prevented the conversion. }
Free Pascal Compiler version 3.2.2 [2021/10/28] for x86_64Copyright (c) 1993-2021 by Florian Klaempfl and othersTarget OS: Darwin for x86_64Compiling arrVariantIsNumeric.pasAssembling arrvariantisnumericLinking arrVariantIsNumeric37 lines compiled, 0.3 secElement 0: Non-Numeric Value - HelloElement 1: Numeric Value - 4.20000000000000000000E+0001Element 2: Numeric Value - 3.14158999999999999993E+0000Element 3: Non-Numeric Value - WorldElement 4: Numeric Value - 9.90000000000000000000E+0001Element 5: Numeric Value - 7.77000000000000000000E+0002Element 6: Non-Numeric Value - $A1
FreeBASIC has a built-in Val() function which converts numeric strings to doubles. However, it is not ideal for the present tasksince it will try to convert as much of the string as it can (so "123xyz" would convert to 123) and return 0 if a conversion onthis basis is not possible (i.e. "xyz" would return 0).
I've therefore written a custom function which recognizes signed numbers in bases from 2 to 16 (but only integral numbers for bases other than 10). For base 10, it will treat "123." or ".123" as numbers but not ".". It doesn't recognize scientific notation but does recognize the integral prefixes &H, &O and &B if bases 16, 8 or 2 respectively are specified.
' FB 1.05.0 Win64DimSharedsymbols(0To15)AsUByteForiAsInteger=48to57symbols(i-48)=iNextForiAsInteger=97to102symbols(i-87)=iNextConstplusAsUByte=43ConstminusAsUbyte=45ConstdotAsUByte=46FunctionisNumeric(sAsConstString,base_AsInteger=10)AsBooleanIfs=""OrElses="."OrElses="+"OrElses="-"ThenReturnFalseErr=0Ifbase_<2OrElsebase_>16ThenErr=1000ReturnFalseEndIfDimtAsString=LCase(s)If(t[0]=plus)OrElse(t[0]=minus)Thent=Mid(t,2)EndIfIfLeft(t,2)="&h"ThenIfbase_<>16ThenReturnFalset=Mid(t,3)EndifIfLeft(t,2)="&o"ThenIfbase_<>8ThenReturnFalset=Mid(t,3)EndifIfLeft(t,2)="&b"ThenIfbase_<>2ThenReturnFalset=Mid(t,3)EndifIfLen(t)=0ThenReturnFalseDimAsBooleanisValid,hasDot=falseForiAsInteger=0ToLen(t)-1isValid=FalseForjAsInteger=0Tobase_-1Ift[i]=symbols(j)ThenisValid=TrueExitForEndIfIft[i]=dotThenIfCInt(NothasDot)AndAlso(base_=10)ThenhasDot=TrueIsValid=TrueExitForEndIfReturnFalse' either more than one dot or not base 10EndIfNextjIfNotisValidThenReturnFalseNextiReturnTrueEndFunctionDimsAsStrings="1234.056789"Prints," (base 10) => ";isNumeric(s)s="1234.56"Prints," (base 7) => ";isNumeric(s,7)s="021101"Prints," (base 2) => ";isNumeric(s,2)s="Dog"Prints," (base 16) => ";isNumeric(s,16)s="Bad125"Prints," (base 16) => ";isNumeric(s,16)s="-0177"Prints," (base 8) => ";isNumeric(s,8)s="+123abcd.ef"Prints," (base 16) => ";isNumeric(s,8)s="54321"Prints," (base 6) => ";isNumeric(s,6)s="123xyz"Prints," (base 10) => ";isNumeric(s)s="xyz"Prints," (base 10) => ";isNumeric(s)PrintPrint"Press any key to quit"Sleep
1234.056789 (base 10) => true1234.56 (base 7) => false021101 (base 2) => falseDog (base 16) => falseBad125 (base 16) => true-0177 (base 8) => true+123abcd.ef (base 16) => false54321 (base 6) => true123xyz (base 10) => falsexyz (base 10) => false
include "NSLog.incl"local fn StringIsNumeric( string as CFStringRef ) as BOOL BOOL flag = NO ScannerRef scanner = fn ScannerWithString( string ) if ( fn ScannerScanFloat( scanner, NULL ) ) flag = fn ScannerIsAtEnd( scanner ) end ifend fn = flagNSLog(@"%d",fn StringIsNumeric( @"1.23" ))NSLog(@"%d",fn StringIsNumeric( @"-123.4e5" ))NSLog(@"%d",fn StringIsNumeric( @"alpha" ))HandleEvents
110
PublicSubForm_Open()DimsAnswer,sStringAsStringsString=Trim(InputBox("Enter as string","String or Numeric"))IfIsNumber(sString)ThensAnswer="'"&sString&"' is numeric"ElsesAnswer="'"&sString&"' is a string"PrintsAnswerEnd
Output:
'Charlie' is a string'-00.256666' is numeric
This uses a library function to meet the task's requirements:
packagemainimport("fmt""strconv")funcisNumeric(sstring)bool{_,err:=strconv.ParseFloat(s,64)returnerr==nil}funcmain(){fmt.Println("Are these strings numeric?")strings:=[]string{"1","3.14","-100","1e2","NaN","rose"}for_,s:=rangestrings{fmt.Printf(" %4s -> %t\n",s,isNumeric(s))}}
Are these strings numeric? 1 -> true 3.14 -> true -100 -> true 1e2 -> true NaN -> true rose -> false
This uses both a library function and a custom one but only checks for integerness:
packagemainimport("fmt""strconv""unicode")funcisInt(sstring)bool{for_,c:=ranges{if!unicode.IsDigit(c){returnfalse}}returntrue}funcmain(){fmt.Println("Are these strings integers?")v:="1"b:=falseif_,err:=strconv.Atoi(v);err==nil{b=true}fmt.Printf(" %3s -> %t\n",v,b)i:="one"fmt.Printf(" %3s -> %t\n",i,isInt(i))}
Are these strings integers? 1 -> true one -> false
Basically a translation of the regex/-?[0-9]+/.
{ .0=45={(;}* '0123456789'-,!} :isnum;'-6' isnum p'6' isnum p'abc' isnum p"3-2" isnum1100
Use the positional parser in java.text.NumberFormat. If, after parsing, the parse position is at the end of the string, we can deduce that the entire string was a valid number.
defisNumeric={defformatter=java.text.NumberFormat.instancedefpos=[0]asjava.text.ParsePositionformatter.parse(it,pos)// if parse position index has moved to end of string// them the whole string was numericpos.index==it.size()}
Test Program:
printlnisNumeric('1')printlnisNumeric('-.555')printlnisNumeric('1,000,000')printlnisNumeric(' 1 1 1 1 ')printlnisNumeric('abcdef')
truetruetruefalsefalse
This function is not particularly useful in a statically typed language. Instead, one would just attempt to convert the stringto the desired type withread orreads, and handle parsing failure appropriately.
The task doesn't define which strings are considered "numeric", so we do Integers and Doubles, which should catch the most common cases (including hexadecimal 0x notation):
isIntegers=casereadss::[(Integer,String)]of[(_,"")]->True_->FalseisDoubles=casereadss::[(Double,String)]of[(_,"")]->True_->FalseisNumeric::String->BoolisNumerics=isIntegers||isDoubles
One can easily addisRational,isComplex etc. following the same pattern.
Another way would be to use the Data.Char module, allowing code such as:
areDigits=allisDigitisDigitselectsASCIIdigitsi.e.'0'..'9'isOctDigitselects'0'..'7'isHexDigitselects'0'..'9','A'..'F','a'..'f'
so read s::Int (for instance) could be reliably used if string s passed these tests.
Haxe has a built-in function that will convert a string to an integer, so we can use that to determine if the string is numeric or not.
staticfunctionisNumeric(n:String):Bool{if(Std.parseInt(n)!=null)//Std.parseInt converts a string to an int{returntrue;//as long as it results in an integer, the function will return true}else{returnfalse;}}
! = bin + 2*int + 4*flt + 8*oct +16*hex + 32*sci isNumeric("1001") ! 27 = 1 1 0 1 1 0 isNumeric("123") ! 26 = 0 1 0 1 1 0 isNumeric("1E78") ! 48 = 0 0 0 0 1 1 isNumeric("-0.123") ! 4 = 0 0 1 0 0 1 isNumeric("-123.456e-78") ! 32 = 0 0 0 0 0 1 isNumeric(" 123") ! 0: leading blank isNumeric("-123.456f-78") ! 0: illegal character fFUNCTION isNumeric(string) ! true ( > 0 ), no leading/trailing blanks CHARACTER string b = INDEX(string, "[01]+", 128, Lbin) ! Lbin returns length found i = INDEX(string, "-?\d+", 128, Lint) ! regular expression: 128 f = INDEX(string, "-?\d+\.\d*", 128, Lflt) o = INDEX(string, "[0-7]+", 128, Loct) h = INDEX(string, "[0-9A-F]+", 128, Lhex) ! case sensitive: 1+128 s = INDEX(string, "-?\d+\.*\d*E[+-]*\d*", 128, Lsci) IF(anywhere) THEN ! 0 (false) by default isNumeric = ( b > 0 ) + 2*( i > 0 ) + 4*( f > 0 ) + 8*( o > 0 ) + 16*( h > 0 ) + 32*( s > 0 ) ELSEIF(boolean) THEN ! 0 (false) by default isNumeric = ( b + i + f + o + h + s ) > 0 ! this would return 0 or 1 ELSE L = LEN(string) isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L) ENDIF ENDconcept numeric(n) {number(n)errors {print(n, " is not numeric!")return}print(n, " is numeric :)")}software {numeric("1200")numeric("3.14")numeric("3/4")numeric("abcdefg")numeric("1234test")}The code writes a printable image of x whatever type it is and a statement about whether it is numeric or not. Icon and Unicon use success and failure instead of boolean functions, numeric(x) is built-in and returns x or fails.
write(image(x),ifnumeric(x)then" is numeric."else" is not numeric")
functionisnumeric,inputon_ioerror,falsetest=double(input)return,1false:return,0end
Could be called like this:
ifisnumeric('-123.45e-2')thenprint,'yes'elseprint,'no'; ==> yesifisnumeric('picklejuice')thenprint,'yes'elseprint,'no'; ==> no
Non-null and non-false values are truthy in Insitux. The operationto-num returns null if it is unable to parse its string parameter, else the parsed number. The operationbool is unnecessary in most situations, but is composed withto-num here to satisfy the task specification.
> (var numeric? (comp to-num bool))(comp to-num bool)> (numeric? "123")true> (numeric? "0x25")true> (numeric? "0b0101")true> (numeric? "hello")false> (numeric? "123x456")false
isNumeric=:_~:_".]isNumericScalar=:1-:isNumericTXT=:,&' a scalar numeric value.'&.>' is not';' represents'sayIsNumericScalar=:,TXT{::~isNumericScalar
Examples of use:
isNumeric'152'1isNumeric'152 -3.1415926 Foo123'110isNumeric'42 foo42 4.2e1 4200e-2 126r3 16b2a 42foo'1011110isNumericScalar'152 -3.1415926 Foo123'0sayIsNumericScalar'-3.1415926'-3.1415926representsascalarnumericvalue.
Typically, you would use the 'parse' methods from either theInteger,Long,Float, orDouble class,
which will throw aNumberFormatException for ill-formed values.
For example
Integer.parseInt("12345")
Float.parseFloat("123.456")
The performance mark is somewhat negligible between a try-block and custom methods.
publicstaticvoidmain(String[]args){Stringvalue;value="1234567";System.out.printf("%-10s %b%n",value,isInteger(value));value="12345abc";System.out.printf("%-10s %b%n",value,isInteger(value));value="-123.456";System.out.printf("%-10s %b%n",value,isFloatingPoint(value));value="-.456";System.out.printf("%-10s %b%n",value,isFloatingPoint(value));value="123.";System.out.printf("%-10s %b%n",value,isFloatingPoint(value));value="123.abc";System.out.printf("%-10s %b%n",value,isFloatingPoint(value));}staticbooleanisInteger(Stringstring){Stringdigits="0123456789";for(charcharacter:string.toCharArray()){if(!digits.contains(String.valueOf(character)))returnfalse;}returntrue;}staticbooleanisFloatingPoint(Stringstring){/* at least one decimal-point */intindexOf=string.indexOf('.');if(indexOf==-1)returnfalse;/* assure only 1 decimal-point */if(indexOf!=string.lastIndexOf('.'))returnfalse;if(string.charAt(0)=='-'||string.charAt(0)=='+'){string=string.substring(1);indexOf--;}Stringinteger=string.substring(0,indexOf);if(!integer.isEmpty()){if(!isInteger(integer))returnfalse;}Stringdecimal=string.substring(indexOf+1);if(!decimal.isEmpty())returnisInteger(decimal);returntrue;}
1234567 true12345abc false-123.456 true-.456 true123. true123.abc false
It's generally bad practice in Java to rely on an exception being thrown since exception handling is relatively expensive. If non-numeric strings are common, you're going to see a huge performance hit.
publicbooleanisNumeric(Stringinput){try{Integer.parseInt(input);returntrue;}catch(NumberFormatExceptione){// s is not numericreturnfalse;}}
Alternative 1 : Check that each character in the string is number. Note that this will only works for integers.
privatestaticfinalbooleanisNumeric(finalStrings){if(s==null||s.isEmpty())returnfalse;for(intx=0;x<s.length();x++){finalcharc=s.charAt(x);if(x==0&&(c=='-'))continue;// negativeif((c>='0')&&(c<='9'))continue;// 0 - 9returnfalse;// invalid}returntrue;// valid}
Alternative 2 : use a regular expression (a more elegant solution).
publicstaticbooleanisNumeric(StringinputData){returninputData.matches("[-+]?\\d+(\\.\\d+)?");}
Alternative 3 : use the positional parser in the java.text.NumberFormat object (a more robust solution). If, after parsing, the parse position is at the end of the string, we can deduce that the entire string was a valid number.
publicstaticbooleanisNumeric(StringinputData){NumberFormatformatter=NumberFormat.getInstance();ParsePositionpos=newParsePosition(0);formatter.parse(inputData,pos);returninputData.length()==pos.getIndex();}
Alternative 4 : use the java.util.Scanner object. Very useful if you have to scan multiple entries.
publicstaticbooleanisNumeric(StringinputData){Scannersc=newScanner(inputData);returnsc.hasNextInt();}
Scanner also has similar methods for longs, shorts, bytes, doubles, floats, BigIntegers, and BigDecimals as well as methods for integral types where you may input a base/radix other than 10 (10 is the default, which can be changed using the useRadix method).
A far better validator can be found on StackOverflow[1]
functionisNumeric(n){return!isNaN(parseFloat(n))&&isFinite(n);}varvalue="123.45e7";// Assign string literal to valueif(isNumeric(value)){// value is a number}//Or, in web browser in address field:// #"/wiki/Category:Jq" title="Category:Jq">jq
Works with jq, the C implementation of jq
Works with gojq, the Go implementation of jq
Works with jaq, the Rust implementation of jq
The simplest way to test if a string can be parsed as a number is:
try tonumber catch false
The above expression will emit the corresponding number, or false if there is none. Here then is a boolean filter which will also emit true for each input that is a number:
def is_numeric: true and try tonumber catch false;
The functionisnumber tests for strings that parse directly to numbers. This test excludes symbols, such as π and1 + 1, that evaluate to numbers as well as certain elaborate numbers (large integers, rationals and complex numbers) whose literals parse to expressions that must be evaluated to yield numbers.
usingPrintfisnumber(s::AbstractString)=tryparse(Float64,s)isaNumbertests=["1","-121","one","pi","1 + 1","NaN","1234567890123456789","1234567890123456789123456789","1234567890123456789123456789.0","1.3","1.4e10","Inf","1//2","1.0 + 1.0im"]fortintestsfl=isnumber(t)?"is":"is not"@printf("%35s%s a direct numeric literal.\n",t,fl)end
1 is a direct numeric literal. -121 is a direct numeric literal. one is not a direct numeric literal. pi is not a direct numeric literal. 1 + 1 is not a direct numeric literal. NaN is a direct numeric literal. 1234567890123456789 is a direct numeric literal. 1234567890123456789123456789 is a direct numeric literal. 1234567890123456789123456789.0 is a direct numeric literal. 1.3 is a direct numeric literal. 1.4e10 is a direct numeric literal. Inf is a direct numeric literal. 1//2 is not a direct numeric literal. 1.0 + 1.0im is not a direct numeric literal.
// version 1.1funisNumeric(input:String):Boolean=try{input.toDouble()true}catch(e:NumberFormatException){false}funmain(args:Array<String>){valinputs=arrayOf("152","-3.1415926","Foo123","-0","456bar","1.0E10")for(inputininputs)println("$input is ${if (isNumeric(input)) "numeric" else "notnumeric"}")}
152 is numeric-3.1415926 is numericFoo123 is not numeric-0 is numeric456bar is not numeric1.0E10 is numeric
This image is aVI Snippet, an executable image ofLabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
local(str='12345')string_isNumeric(#str)// true
'12345'->isdigit// true'1X34Q'->isdigit// false
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"while n$ <> "end" read n$ print n$, IsNumber(n$)wendendfunction 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
"123457".is_integer.println;// write TRUE on stdin
show number? "-1.23 ; true
This will also accept strings like "0xFF" or "314.16e-2" as numbers.
iftonumber(a)~=nilthen--it's a numberend;
We have to define our IsNumber()Version 2 handle decimal point character. For code M2000 use dot, but for input and output use the user specified decimal point, from OS. Function Str$(1.2) return a string with a dot always, but if we place a second parameter this change. Print str$(1.2, "") maybe return 1,2 and nor 1.2. Print str$(1.2, "#.00") maybe return 1.20 or 1,20. The reverse function is Val() which can take more characters so A Val("121mm") is 121, and with a second parameter we can interpret properly the decimal dot: Print Val("1.2", ".") always return 1.2 double. Print Val("1,2", ",")=1.2 return true, 1.2 is a m2000 number literal and always has a dot.
\\ version 2Module Checkit { function global isNumber(a$, de$=".") { =false=true ' return boolean if de$="" then de$=str$(.1,".") ' get current decimal point character a$=trim$(ucase$(a$)) m=len(a$) if m=0 then exit c$=filter$(a$,"0123456789") if c$ = "" then { =true } else.if m>1 then { \ may have -+ and , if m=2 then { if not c$~"[-+\"+de$+"]" then break } else { if left$(c$,1 ) ~"[+-]" then c$=mid$(c$, 2) if not (c$=de$ or c$=de$+"E" or c$ ~ de$+"E[+-]") then break if c$ ~ de$+"E[+-]" then if not (instr(a$,"E+")>0 or instr(a$,"E-")>0) then break } if de$<>"." then a$=replace$(de$, ".", a$, 1,1) try {inline "a="+a$+"=="+a$} if valid(a) then =a = true=true ' return boolean } } Print isNumber("+1"), isnumber("-1"), isNumber("1+")=false, isnumber("1-")=false Print isNumber(",1",","), isnumber("1,",","), isNumber(",0",","), isnumber("0,", ",") Print isNumber(".1"), isnumber("1."), isNumber(".0"), isnumber("0.") Print isNumber("+.1"), isnumber("-1."), isNumber(".12e+232"), isnumber("0.122e10") Print isNumber("+.1a")=false, isnumber("asasa1212")=false, isNumber("1.2e43+23")=false, isnumber("0.122e10") Print isNumber("1221.211.1221")=false, isnumber("1221e1212")=false, isNumber("1.2e4323")=false, isnumber("-.122e-10")}CheckitFrom rev.31 Version 9.3 Val function update, to include a more quick version of above. We have to specify the dot char or write any two or more chars for dot to get integer part. Val function return number and in third argument (passing by reference by default) return first position in string after number. If string is empty or have no number then position is -1. If a number found position is >1. Leading spaces trimmed.
Function IsNumeric(a$) { def m =val(false->boolean) Try { if islet then { z=val(a$,letter$, m) } else.if isnum then { z=val(a$,number, m) } else z=val(a$,"", m) =m>len(a$) }}Function IsIntegerNumeric(a$) { def m =val(false->boolean) Try { z=val(a$,"Int", m) =m>len(a$) }}Locale 1033 ' to use . as decimal, else we have to place 1033 or "." as second parameterPrint isNumeric("+1"), isNumeric("-1"), isNumeric("1+")=false, isNumeric("1-")=falsePrint isNumeric(",1",","), isNumeric("1,",","), isNumeric(",0",","), isNumeric("0,", ",")Print isNumeric(".1"), isNumeric("1."), isNumeric(".0"), isNumeric("0.")Print isNumeric("+.1"), isNumeric("-1."), isNumeric(".12e+232"), isNumeric("0.122e10")Print isNumeric("+.1a")=false, isNumeric("asasa1212")=false, isNumeric("1.2e43+23")=false, isNumeric("0.122e10")Print isNumeric("1221.211.1221")=false, isNumeric("1221e1212")=false, isNumeric("1.2e4323")=false, isNumeric("-.122e-10")isNumeric:=proc(s)tryiftype(parse(s),numeric)thenprintf("The string is numeric."):elseprintf("The string is not numeric."):endif:catch:printf("The string is not numeric."):endtry:endproc:
NumberQ[ToExpression["02553352000242"]]
functionr=isnum(a)r=~isnan(str2double(a))end% testsdisp(isnum(123))% 1disp(isnum("123"))% 1disp(isnum("foo123"))% 0disp(isnum("123bar"))% 0disp(isnum("3.1415"))% 1
numberp(parse_string("170141183460469231731687303715884105727"));
fn isNumeric str =( try ( (str as integer) != undefined ) catch(false))isNumeric "123"
( dup (((int integer?) (pop false)) try) dip ((float float?) (pop false)) try or) :numeric?
We rely on conversion to number returning a nonzero number, plus special checks for zero strings. Note that theval function is forgiving about additional charactersafter the number, so our function is too.
isNumeric=function(s)returns=="0"ors=="-0"orval(s)!=0endfunctionprintisNumeric("0")printisNumeric("42")printisNumeric("-3.14157")printisNumeric("5@*#!")printisNumeric("spam")
11110
# $a0 char val# $a1 address pointer# $a2 PERIOD_HIT_FLAG# $a3 HAS_DIGITS_FLAG.data### CHANGE THIS STRING TO TEST DIFFERENT ONES... ###string:.asciiz"-.1236"s_false:.asciiz"False"s_true:.asciiz"True".textmain:set_up:#test for 0th char == 45 or 46 or 48...57la$a1,stringlb$a0,($a1)beq$a0,45,loop# == '-'beq$a0,46,loop# == '.'blt$a0,48,exit_false# isn't below the ascii range for chars '0'...'9'bgt$a0,57,exit_false# isn't above the ascii range for chars '0'...'9'loop:addi$a1,$a1,1lb$a0,($a1)beqz$a0,exit_true# test for \0 null charbeq$a0,46,period_test#test for a duplicate periodblt$a0,48,exit_false#test forbgt$a0,57,exit_falsela$a3,1#set the HAS_DIGITS flag. This line is only reached because the# tests for period and - both jump back to start.jloopexit_true:beqz$a3,exit_falsela$a0,s_truela$v0,4syscallli$v0,10syscallexit_false:la$a0,s_falsela$v0,4syscallli$v0,10syscallperiod_test:beq$a2,1,exit_falseli$a2,1jloop
import java.text.NumberFormatimport java.text.ParsePositionimport java.util.Scanner# this first example relies on catching an exception, # which is bad style and poorly performing in Javadef is_numeric?(s:string) begin Double.parseDouble(s) return true rescue return false endendputs '123 is numeric' if is_numeric?('123')puts '-123 is numeric' if is_numeric?('-123')puts '123.1 is numeric' if is_numeric?('123.1')puts 'nil is not numeric' unless is_numeric?(nil)puts "'' is not numeric" unless is_numeric?('')puts 'abc is not numeric' unless is_numeric?('abc')puts '123- is not numeric' unless is_numeric?('123-')puts '1.2.3 is not numeric' unless is_numeric?('1.2.3')# check every element of the stringdef is_numeric2?(s: string) if (s == nil || s.isEmpty()) return false end if (!s.startsWith('-')) if s.contains('-') return false end end 0.upto(s.length()-1) do |x| c = s.charAt(x) if ((x == 0) && (c == '-'.charAt(0))) # negative number elsif (c == '.'.charAt(0)) if (s.indexOf('.', x) > -1) return false # more than one period end elsif (!Character.isDigit(c)) return false end end trueendputs '123 is numeric' if is_numeric2?('123')puts '-123 is numeric' if is_numeric2?('-123')puts '123.1 is numeric' if is_numeric2?('123.1')puts 'nil is not numeric' unless is_numeric2?(nil)puts "'' is not numeric" unless is_numeric2?('')puts 'abc is not numeric' unless is_numeric2?('abc')puts '123- is not numeric' unless is_numeric2?('123-')puts '1.2.3 is not numeric' unless is_numeric2?('1.2.3')# use a regular expression def is_numeric3?(s:string) s == nil || s.matches("[-+]?\\d+(\\.\\d+)?")endputs '123 is numeric' if is_numeric3?('123')puts '-123 is numeric' if is_numeric3?('-123')puts '123.1 is numeric' if is_numeric3?('123.1')puts 'nil is not numeric' unless is_numeric3?(nil)puts "'' is not numeric" unless is_numeric3?('')puts 'abc is not numeric' unless is_numeric3?('abc')puts '123- is not numeric' unless is_numeric3?('123-')puts '1.2.3 is not numeric' unless is_numeric3?('1.2.3')# use the positional parser in the java.text.NumberFormat object # (a more robust solution). If, after parsing, the parse position is at # the end of the string, we can deduce that the entire string was a # valid number.def is_numeric4?(s:string) return false if s == nil formatter = NumberFormat.getInstance() pos = ParsePosition.new(0) formatter.parse(s, pos) s.length() == pos.getIndex()endputs '123 is numeric' if is_numeric4?('123')puts '-123 is numeric' if is_numeric4?('-123')puts '123.1 is numeric' if is_numeric4?('123.1')puts 'nil is not numeric' unless is_numeric4?(nil)puts "'' is not numeric" unless is_numeric4?('')puts 'abc is not numeric' unless is_numeric4?('abc')puts '123- is not numeric' unless is_numeric4?('123-')puts '1.2.3 is not numeric' unless is_numeric4?('1.2.3')# use the java.util.Scanner object. Very useful if you have to # scan multiple entries. Scanner also has similar methods for longs, # shorts, bytes, doubles, floats, BigIntegers, and BigDecimals as well # as methods for integral types where you may input a base/radix other than # 10 (10 is the default, which can be changed using the useRadix method).def is_numeric5?(s:string) return false if s == nil Scanner sc = Scanner.new(s) sc.hasNextDouble()endputs '123 is numeric' if is_numeric5?('123')puts '-123 is numeric' if is_numeric5?('-123')puts '123.1 is numeric' if is_numeric5?('123.1')puts 'nil is not numeric' unless is_numeric5?(nil)puts "'' is not numeric" unless is_numeric5?('')puts 'abc is not numeric' unless is_numeric5?('abc')puts '123- is not numeric' unless is_numeric5?('123-')puts '1.2.3 is not numeric' unless is_numeric5?('1.2.3')var %value = 3if (%value isnum) { echo -s %value is numeric.}MODULENumericEXPORTSMain;IMPORTIO,Fmt,Text;PROCEDUREisNumeric(s:TEXT):BOOLEAN=BEGINFORi:=0TOText.Length(s)DOWITHchar=Text.GetChar(s,i)DOIFi=0ANDchar='-'THENEXIT;END;IFchar>='0'ANDchar<='9'THENEXIT;END;RETURNFALSE;END;END;RETURNTRUE;ENDisNumeric;BEGINIO.Put("isNumeric(152) = "&Fmt.Bool(isNumeric("152"))&"\n");IO.Put("isNumeric(-3.1415926) = "&Fmt.Bool(isNumeric("-3.1415926"))&"\n");IO.Put("isNumeric(Foo123) = "&Fmt.Bool(isNumeric("Foo123"))&"\n");ENDNumeric.
isNumeric(152) = TRUEisNumeric(-3.1415926) = TRUEisNumeric(Foo123) = FALSE
In MUMPS, strings are automatically converted to numbers when a unary or binary arithmetic operator works upon them. If there are no leading digits, a string converts to zero. If there a string of digits followed by an "e" or an "E" followed in turn by more digits, the numbers after the letter are treated as an exponent.
Examples from command line:
USER>WRITE +"1"1USER>WRITE +"1A"1USER>WRITE +"A1"0USER>WRITE +"1E"1USER>WRITE +"1E2"100USER>WRITE +"1EA24"1USER>WRITE +"1E3A"1000USER>WRITE +"1E-3".001
There is a function, $ISVALIDNUM, to do the testing.
USER>WRITE $SELECT($ISVALIDNUM("123"):"Valid",1:"Invalid"),!Valid USER>WRITE $SELECT($ISVALIDNUM("a123"):"Valid",1:"Invalid"),!Invalid USER>WRITE $SELECT($ISVALIDNUM("123a"):"Valid",1:"Invalid"),!InvalidUSER>WRITE $SELECT($ISVALIDNUM("123e4"):"Valid",1:"Invalid"),!Validdef isNum(str) try double(str) return true catch return false endend
usingSystem;usingSystem.Console;moduleIsNumeric{IsNumeric(input:string):bool{mutablemeh=0.0;// I don't want it, not going to use it, why force me to declare it?double.TryParse(input,outmeh)}Main():void{defnum="-1.2345E6";defnot="abc45";WriteLine($"$num is numeric:$(IsNumeric(num))");WriteLine($"$not is numeric:$(IsNumeric(not))");}}
/* NetRexx */optionsreplaceformatcommentsjavacrossrefsymbolsnobinarynumericdigits20loopn_overgetTestData()--couldhaveusedn_.datatype('N')directlyhere...ifisNumeric(n_)thenmsg='numeric'elsemsg='not numeric'say('"'n_'"').right(25)':'msgendn_return--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--PointlessinNetRexx;theDATATYPEbuilt-in-functionismorepowerful!methodisNumeric(testString)publicstaticreturnsbooleanreturntestString.datatype('N')--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~methodgetTestData()privatestaticreturnsRexx[]--CoercingnumbersintotheRexxtypehastheeffectofconvertingthemtostrings.--NetRexxwillstillperformarithmeticonRexxstringsifthosestringsrepresentnumbers.--NoticethatwhitespacebetweenthesignandthenumberareignoredevenwheninsideastringconstanttestData=[Rexx-' one and a half',1,1.5,1.5e+27,' 1 ',' 1.5 ',' 1.5e+27 ',-'-one and a half',-1,-1.5,-1.5e-27,' - 1 ','- 1.5 ','- 1.5e-27 ',-'+one and a half',+1,+1.5,+1.5e+27,' + 1 ','+ 1.5 ','+ 1.5e+27 ',-'Math Constants',-Math.PI,Math.E,--Math.PI,-Math.E,-+Math.PI,+Math.E,-'Numeric Constants',-Double.NaN,Double.POSITIVE_INFINITY,Double.NEGATIVE_INFINITY-]returntestData
" one and a half": not numeric "1": numeric "1.5": numeric "1.5e+27": numeric " 1 ": numeric " 1.5 ": numeric " 1.5e+27 ": numeric "-one and a half": not numeric "-1": numeric "-1.5": numeric "-1.5E-27": numeric " - 1 ": numeric "- 1.5 ": numeric "- 1.5e-27 ": numeric "+one and a half": not numeric "1": numeric "1.5": numeric "1.5E+27": numeric " + 1 ": numeric "+ 1.5 ": numeric "+ 1.5e+27 ": numeric "Math Constants": not numeric "3.141592653589793": numeric "2.718281828459045": numeric "-3.141592653589793": numeric "-2.718281828459045": numeric "3.141592653589793": numeric "2.718281828459045": numeric "Numeric Constants": not numeric "NaN": not numeric "Infinity": not numeric "Infinity": not numeric
importstrutilsprocisNumeric(s:string):bool=try:discards.parseFloat()result=trueexceptValueError:result=falseconstStrings=["1","3.14","-100","1e2","Inf","rose"]forsinStrings:echos," is ",ifs.isNumeric():""else:"not ","numeric"
We could prefer to use the “parsutils” module which avoids the exception:
importparseutilsprocisNumeric(s:string):bool=varx:floats.parseFloat(x)==s.lenconstStrings=["1","3.14","-100","1e2","Inf","rose"]forsinStrings:echos," is ",ifs.isNumeric():""else:"not ","numeric"
1 is numeric3.14 is numeric-100 is numeric1e2 is numericInf is numericrose is not numeric
The code below is not a function because the Pep/nom system is completelytext-oriented that is, it is designed to consume a text (unicode) input stream and produce a text output stream. The code just prints a message indicating that the input is numeric or not.It is simple to modify this to recogniseall numeric values in the given text. Just parse all non-numeric characters as a text* parse tokenand check if the preceding token was a number (signed/unsigned/decimal).
I use the word "float*" for thedecimal number type, which is probablya bad choice of name.
By defaultNom uses the '*' character as the parse token delimiter butthis can be modified, for example in thebegin block of the script
begin { delim "/"; }#*GRAMMAR OR PARSE TOKENS int* - an unsigned integer sint* - a +/- signed integer .* - decimal pointHISTORY 12 sept 2021: written, working*# # remove leading space begin { while [:space:]; clear; } read; [0-9] { while [0-9]; put; clear; add "int*"; push; .reparse } [.+-] { put; add "*"; push; .reparse } [:space:] { while [:space:]; clear; add "space*"; push; .reparse } !"" { put; clear; add "Non-numeric char at "; lines; add ":"; chars; add "\n"; print; quit; }parse> # To visualise token reduction uncomment this: #lines; add ":"; chars; add " "; print; clear; #add "\n"; unstack; print; clip; stack; pop; pop; # ------------- # 2 tokens "+*int*","-*int*" { clear; add "sint*"; push; .reparse } pop; # ------------- # 3 tokens "sint*.*int*","int*.*int*" { clear; add "float*"; push; .reparse } (eof) { # ignore trailing space stack; pop; "space*" { clear; } unstack; "int*","sint*","float*" { replace "sint*" "signed integer,"; replace "int*" "integer,"; replace "*" ","; put; clear; add "It looks like a number (of type "; get; add ")\n"; print; quit; } replace "sint*" "signed integer,"; replace "int*" "integer,"; replace "*" ","; put; clear; add "Doesnt look like one number \n"; add "It was parsed as '"; get; add "'\n"; print; quit; } push; push; push;def is-numeric [] {try {into float | true} catch {false}}["1" "12" "-3" "5.6" "-3.14" "one" "cheese"] | each {{k: $in, v: ($in | is-numeric)}}╭───┬────────┬───────╮│ # │ k │ v │├───┼────────┼───────┤│ 0 │ 1 │ true ││ 1 │ 12 │ true ││ 2 │ -3 │ true ││ 3 │ 5.6 │ true ││ 4 │ -3.14 │ true ││ 5 │ one │ false ││ 6 │ cheese │ false │╰───┴────────┴───────╯
class Numeric { function : Main(args : String[]) ~ Nil { if(args->Size() = 1) { IsNumeric(args[0])->PrintLine(); }; } function : IsNumeric(str : String) ~ Bool { return str->IsFloat(); }}TheNSScanner class supports scanning of strings for various types. ThescanFloat method will return YES if the string is numeric, even if the number is actually too long to be contained by the precision of afloat.
if([[NSScannerscannerWithString:@"-123.4e5"]scanFloat:NULL])NSLog(@"\"-123.4e5\" is numeric");elseNSLog(@"\"-123.4e5\" is not numeric");if([[NSScannerscannerWithString:@"Not a number"]scanFloat:NULL])NSLog(@"\"Not a number\" is numeric");elseNSLog(@"\"Not a number\" is not numeric");// prints: "-123.4e5" is numeric// prints: "Not a number" is not numeric
The following function can be used to check if a string is numeric "totally"; this is achieved by checking if the scanner reached the end of the string after the float is parsed.
BOOL isNumeric(NSString *s){ NSScanner *sc = [NSScanner scannerWithString: s]; if ( [sc scanFloat:NULL] ) { return [sc isAtEnd]; } return NO;}If we want to scanby hand, we could use a function like the following, that checks if a number is an integer positive or negative number; spaces can appear at the beginning, but not after the number, andthe '+' or '-' can appear onlyattached to the number ("+123" returns YES, but "+ 123" returns NO).
BOOL isNumericI(NSString *s){ NSUInteger len = [s length]; NSUInteger i; BOOL status = NO; for(i=0; i < len; i++) { unichar singlechar = [s characterAtIndex: i]; if ( (singlechar == ' ') && (!status) ) { continue; } if ( ( singlechar == '+' || singlechar == '-' ) && (!status) ) { status=YES; continue; } if ( ( singlechar >= '0' ) && ( singlechar <= '9' ) ) { status = YES; } else { return NO; } } return (i == len) && status;}Here we assumed that in the internal encoding of a string (that should be Unicode), 1 comes after 0, 2 after 1 and so on until 9. Another way could be to get the C String from the NSString object, and then the parsing would be the same of the one we could do in standard C, so this path is not given.
This function is not particularly useful in a statically typed language. Instead, one would just attempt to convert the stringto the desired type and handle parsing failure appropriately.
The task doesn't define which strings are considered "numeric", so we do ints and floats, which should catch the most common cases:
let is_int s = try ignore (int_of_string s); true with _ -> falselet is_float s = try ignore (float_of_string s); true with _ -> falselet is_numeric s = is_int s || is_float s
The builtin functionisnumeric return true (1) if the argument is a data of typenumber; the provided functionisnum works the same for numeric datatype, while if another type is passed as argument, it tries to convert it to a number; if the conversion fails, it means it is not a string representing a number.
function r = isnum(a) if ( isnumeric(a) ) r = 1; else r = ~isnan(str2double(a)); endifendfunction% testsdisp(isnum(123)) % 1disp(isnum("123")) % 1disp(isnum("foo123")) % 0disp(isnum("123bar")) % 0disp(isnum("3.1415")) % 1package mainimport "core:strconv"import "core:fmt"is_numeric :: proc(s: string) -> bool { _, ok := strconv.parse_f32(s) return ok}main :: proc() { strings := []string{"1", "3.14", "-100", "1e2", "Inf", "rose"} for s in strings { fmt.println(s, "is", is_numeric(s) ? "numeric" : "not numeric") }}/* Output:1 is numeric3.14 is numeric-100 is numeric1e2 is numericInf is not numericrose is not numeric*/fun {IsNumeric S} {String.isInt S} orelse {String.isFloat S}endisNumeric(s)={ my(t=type(eval(s))); t == "t_INT" || t == "T_REAL"};SeeDelphi orFree Pascal.
function IsNumeric(s: string): boolean;begin var i: integer; Result := integer.TryParse(s,i)end;begin var s := '123'; if IsNumeric(s) then Print('string is numeric')end.Built-In FunctionSyntaxIsNumber(Value)DescriptionUse the IsNumber function to determine if Value contains a valid numeric value. Numeric characters include sign indicators and comma and period decimal points.To determine if a value is a number and if it's in the user's local format, use the IsUserNumber function.ParametersValueSpecify a string you want to search to determine if it is a valid number.ReturnsA Boolean value: True if Value contains a valid numeric value, False otherwise.Example&Value = Get Field().Value; If IsNumber(&Value) Then /* do numeric processing */ Else /* do non-numeric processing */ End-if;
use Scalar::Util qw(looks_like_number);print looks_like_number($str) ? "numeric" : "not numeric\n";
Quoting fromperlfaq4:
How do I determine whether a scalar is a number/whole/integer/float?
Assuming that you don't care aboutIEEE notations like "NaN" or "Infinity", you probably just want to use aregular expression.
if (/\D/) { print "has nondigits\n" }if (/^\d+\z/) { print "is a whole number\n" }if (/^-?\d+\z/) { print "is an integer\n" }if (/^[+-]?\d+\z/) { print "is a +/- integer\n" }if (/^-?\d+\.?\d*\z/) { print "is a real number\n" }if (/^-?(?:\d+(?:\.\d*)?&\.\d+)\z/) { print "is a decimal number\n" }if (/^([+-]?)(?=\d&\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\z/) { print "a C float\n" }There are also some commonly used modules for the task. Scalar::Util (distributed with 5.8) provides access to Perl's internal function "looks_like_number" for determining whether a variable looks like a number. Data::Types exports functions that validate data types using both the above and other regular expressions. Thirdly, there is "Regexp::Common" which has regular expressions to match various types of numbers. Those three modules are available from the CPAN.
If you're on aPOSIX system, Perl supports the "POSIX::strtod" function. Its semantics are somewhat cumbersome, so here's a "getnum" wrapper function for more convenient access. This function takes a string and returns the number it found, or "undef" for input that isn't a C float. The "is_numeric" function is a front end to "getnum" if you just want to say,Is this a float?
sub getnum { use POSIX; my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') && ($unparsed != 0) && $!) { return undef; } else { return $num; }}sub is_numeric { defined getnum($_[0]) }Or you could check out the String::Scanf module on the CPAN instead. The POSIX module (part of the standard Perl distribution) provides the "strtod" and "strtol" for converting strings to double and longs, respectively.
function isNumber(string s) return scanf(s,"%f")!={}-- Alt: isNumberString(object s) and-- return string(s) and scanf(s,"%f")!={}, or even-- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={}end function constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0", "0.","0.0","000.000","0e0","0e-2000"," ", ".14",".05","-5.2","0xf","ten","1B","#1B", " 12 ",trim(" 12 "),"1","0o16","0o18", "0b10101111_11110000_11110000_00110011", "1_000","50e","+123","+ 123","-0b10101", "NaN","+.345","12..34","12e3.4","0-2", "192.168.0.1","1.2e","1 2","12.34","", "beef","#beef","1,000,000","Inf","1/2", "1.5e+27","0x10.5","1."} sequence numeric = {}, notnumb = {}for i=1 to length(tests) do string ti = tests[i] if isNumber(ti) then numeric = append(numeric,ti) else notnumb = append(notnumb,ti) end ifend forputs(1,"numeric: ")pp(numeric,{pp_Indent,9})puts(1,"\nnot numeric: ")pp(notnumb,{pp_Indent,13})numeric: {`#a`, `#A`, `0xA`, `0(16)A`, `#FF`, `255`, `0`, `0.0`, `000.000`, `0e0`, `0e-2000`, `.14`, `.05`, `-5.2`, `0xf`, `#1B`, `12`, `1`, `0o16`, `0b10101111_11110000_11110000_00110011`, `1_000`, `+123`, `-0b10101`, `+.345`, `12.34`, `#beef`, `1.5e+27`, `0x10.5`}not numeric: {`0.`, ` `, `ten`, `1B`, ` 12 `, `0o18`, `50e`, `+ 123`, `NaN`, `12..34`, `12e3.4`, `0-2`, `192.168.0.1`, `1.2e`, `1 2`, ``, `beef`, `1,000,000`, `Inf`, `1/2`, `1.`}Should you want to check for (eg) complex numbers, your best bet is to (also) invoke scanf() with several other different format strings such as "%f+%fi", "%f-%fj" (etc), until one works, or they all fail.
<?php$string = '123';if(is_numeric(trim($string))) {}?>The 'format' function canbe used for that. It returns NIL if the given string is not a legal number
: (format "123")-> 123: (format "123a45")-> NIL: (format "-123.45" 4)-> 1234500
the sscanf format %f will find any kind of number.the %s before and after make sure the number is not surrounded by other text.
int(0..1) is_number(string s){ array test = array_sscanf(s, "%s%f%s"); if (sizeof(test) == 3 && test[1] && !sizeof(test[0]) && !sizeof(test[2]) ) return true; else return false;}string num = "-1.234"is_number(num);-> trueis_numeric: procedure (text) returns (bit (1)); declare text character (*); declare x float; on conversion go to done; get string(text) edit (x) (E(length(text),0)); return ('1'b);done: return ('0'b);end is_numeric;5 '1'B 6.7 '1'B -8.9 '1'B -4e3 '1'B 4A37 '0'B
FUNCTION IsNumeric( value IN VARCHAR2 )RETURN BOOLEANIS help NUMBER;BEGIN help := to_number( value ); return( TRUE );EXCEPTION WHEN others THEN return( FALSE );END;
Value VARCHAR2( 10 ) := '123';IF( IsNumeric( Value ) ) THEN NULL;END IF;
The following decider exists in the noodleTo decide if a string is any numeric literal:
and is used to resolve the If clauseIf the string is any numeric literal,in this solution.
To run:Start up.Show whether "cat" is numeric.Show whether "3" is numeric.Show whether "+3" is numeric.Show whether "-123" is numeric.Show whether "123,456" is numeric.Show whether "11/5" is numeric.Show whether "-26-1/3" is numeric.Show whether "+26-1/3" is numeric.Show whether "1/0" is numeric. \in Plain English, 1/0 is 0. Don't tell the mathematicians!Show whether "3.14159" is numeric. \floating point is not implemented in Plain English.Wait for the escape key.Shut down.To show whether a string is numeric:Write the string then " -> " on the console without advancing.If the string is any numeric literal, write "yes" on the console; exit.Write "no" on the console.
cat -> no3 -> yes+3 -> yes-123 -> yes123,456 -> no11/5 -> yes-26-1/3 -> yes+26-1/3 -> yes1/0 -> yes3.14159 -> no
function chk(a) return tonumber(a) != nilenda = {"123", "-320", "-1342.40", "abc", "1,234", "a123.0"}a:map(chk); print(a:unpack())true true true false false false
Note: PowerShell 1.0 does not support 'try'THis simply tries arithmetic with the argument and if that fails,false is returned.
function isNumeric ($x) { try { 0 + $x | Out-Null return $true } catch { return $false }}But this one doesn't work for strings like "8." though a . is appended it returns true!
Alternatively, you can use the static System.Int32.TryParse() method in the .NET framework.
function isNumeric ($x) { $x2 = 0 $isNum = [System.Int32]::TryParse($x, [ref]$x2) return $isNum}The code:
numeric_string(String) :- atom_string(Atom, String), atom_number(Atom, _).
A predicate to test the code:
test_strings(Strings) :- forall( member(String, Strings), ( ( numeric_string(String) -> Result = a ; Result = 'not a' ), format('~w is ~w number.~n', [String, Result]) ) ).Example of using the test predicate:
?- test_strings(["123", "0.123", "-123.1", "NotNum", "1."]).123 is a number.0.123 is a number.-123.1 is a number.NotNum is not a number.1. is not a number.true.
This routine parses the string to verify it's a number. It returns 1 if string is numeric, 0 if it is not. The character used as the decimal separator may be specified if desired.
Procedure IsNumeric(InString.s, DecimalCharacter.c = '.') #NotNumeric = #False #IsNumeric = #True InString = Trim(InString) Protected IsDecimal, CaughtDecimal, CaughtE Protected IsSignPresent, IsSignAllowed = #True, CountNumeric Protected *CurrentChar.Character = @InString While *CurrentChar\c Select *CurrentChar\c Case '0' To '9' CountNumeric + 1 IsSignAllowed = #False Case DecimalCharacter If CaughtDecimal Or CaughtE Or CountNumeric = 0 ProcedureReturn #NotNumeric EndIf CountNumeric = 0 CaughtDecimal = #True IsDecimal = #True Case '-', '+' If IsSignPresent Or Not IsSignAllowed: ProcedureReturn #NotNumeric: EndIf IsSignPresent = #True Case 'E', 'e' If CaughtE Or CountNumeric = 0 ProcedureReturn #NotNumeric EndIf CaughtE = #True CountNumeric = 0 CaughtDecimal = #False IsSignPresent = #False IsSignAllowed = #True Default ProcedureReturn #NotNumeric EndSelect *CurrentChar + SizeOf(Character) Wend If CountNumeric = 0: ProcedureReturn #NotNumeric: EndIf ProcedureReturn #IsNumericEndProcedureIf OpenConsole() PrintN("'+3183.31151E+321' = " + Str(IsNumeric("+3183.31151E+321"))) PrintN("'-123456789' = " + Str(IsNumeric("-123456789"))) PrintN("'123.45.6789+' = " + Str(IsNumeric("123.45.6789+"))) PrintN("'-e' = " + Str(IsNumeric("-e"))) Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole()EndIf'+3183.31151E+321' = 1'-123456789' = 1'123.45.6789+' = 0'-e' = 0
def is_numeric(s): try: float(s) return True except (ValueError, TypeError): return Falseis_numeric('123.0')Or for positive integers only:
'123'.isdigit()
Including complex, hex, binary, and octal numeric literals we get:
def is_numeric(literal): """Return whether a literal can be parsed as a numeric value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: cast(literal) return True except ValueError: pass return False
Sample use, including value parsed, its type, and standard method str.isnumeric():
def numeric(literal): """Return value of numeric literal or None if can't parse a value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: return cast(literal) except ValueError: pass return Nonetests = [ '0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04', '0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1', '12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02', 'NaN', 'inf', '-Infinity']for s in tests: print("%14s -> %-14s %-20s is_numeric: %-5s str.isnumeric: %s" % ( '"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))"0" -> 0 <class 'int'> is_numeric: True str.isnumeric: True "0." -> 0.0 <class 'float'> is_numeric: True str.isnumeric: False "00" -> 0 <class 'int'> is_numeric: True str.isnumeric: True "123" -> 123 <class 'int'> is_numeric: True str.isnumeric: True "0123" -> 123 <class 'int'> is_numeric: True str.isnumeric: True "+123" -> 123 <class 'int'> is_numeric: True str.isnumeric: False "-123" -> -123 <class 'int'> is_numeric: True str.isnumeric: False "-123." -> -123.0 <class 'float'> is_numeric: True str.isnumeric: False "-123e-4" -> -0.0123 <class 'float'> is_numeric: True str.isnumeric: False "-.8E-04" -> -8e-05 <class 'float'> is_numeric: True str.isnumeric: False "0.123" -> 0.123 <class 'float'> is_numeric: True str.isnumeric: False "(5)" -> (5+0j) <class 'complex'> is_numeric: True str.isnumeric: False "-123+4.5j" -> (-123+4.5j) <class 'complex'> is_numeric: True str.isnumeric: False "0b0101" -> 5 <class 'int'> is_numeric: True str.isnumeric: False " +0B101 " -> 5 <class 'int'> is_numeric: True str.isnumeric: False "0o123" -> 83 <class 'int'> is_numeric: True str.isnumeric: False "-0xABC" -> -2748 <class 'int'> is_numeric: True str.isnumeric: False "0x1a1" -> 417 <class 'int'> is_numeric: True str.isnumeric: False "12.5%" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False "1/2" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False "½" -> None <class 'NoneType'> is_numeric: False str.isnumeric: True "3¼" -> None <class 'NoneType'> is_numeric: False str.isnumeric: True "π" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False "Ⅻ" -> None <class 'NoneType'> is_numeric: False str.isnumeric: True "1,000,000" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False "1 000" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False"- 001.20e+02" -> None <class 'NoneType'> is_numeric: False str.isnumeric: False "NaN" -> nan <class 'float'> is_numeric: True str.isnumeric: False "inf" -> inf <class 'float'> is_numeric: True str.isnumeric: False "-Infinity" -> -inf <class 'float'> is_numeric: True str.isnumeric: False
import renumeric = re.compile('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?')is_numeric = lambda x: numeric.fullmatch(x) != Noneis_numeric('123.0')[ char . over find tuck over found iff [ swap pluck drop ] else nip ] is -point ( $ --> $ ) [ -point $->n nip ] is numeric ( $ --> b ) [ dup echo$ say " is" numeric not if say " not" say " a valid number." cr ] is task ( $ --> ) $ "152" task $ "-3.1415926" task $ "Foo123" task
152 is a valid number.-3.1415926 is a valid number.Foo123 is not a valid number.
> strings <- c("152", "-3.1415926", "Foo123")> suppressWarnings(!is.na(as.numeric(strings)))[1] TRUE TRUE FALSE(define (string-numeric? s) (number? (string->number s)))
Or, since all non-#f are true:
(define string-numeric? string->number)
(formerly Perl 6)
Raku tries very hard to DWIM (do what I mean). As part of that, numeric strings are by default stored as allomorphic types which can be used as numbers or strings without any conversion. If we truly want to operate on strings, we have to explicitly coerce the allomorphs to strings. A subtlety that may not be immediately apparent, whitespace, empty strings and null strings may be treated as (False) boolean values in Raku, however booleans are allomorphic to numeric, so empty strings will coerce to a numeric value (0), and return as numeric unless specifically checked for. Interestingly, the actual strings 'True' and 'False'don't evaluate as numeric. (because there are no String | Boolean allomorphs.)
Note: These routines are usable for most cases but won't detect unicode non-digit numeric forms; E.G. vulgar fractions, Roman numerals, circled numbers, etc. If it is necessary to detect those as numeric, a full fledged grammar may be necessary.
sub is-number-w-ws( Str $term --> Bool ) { # treat Falsey strings as numeric $term.Numeric !~~ Failure;}sub is-number-wo-ws( Str $term --> Bool ) { # treat Falsey strings as non-numeric ?($term ~~ / \S /) && $term.Numeric !~~ Failure;}say " Coerce Don't coerce";say ' String whitespace whitespace';printf "%10s %8s %11s\n","<$_>", .&is-number-w-ws, .&is-number-wo-ws for(|<1 1.2 1.2.3 -6 1/2 12e B17 1.3e+12 1.3e12 -2.6e-3 zero 0x 0xA10 0b1001 0o16 0o18 2+5i True False Inf NaN 0x10.50 0b102 0o_5_3 ௫௯>, ' 12 ', '1 1 1', '', ' ' ).map: *.Str;Coerce Don't coerce String whitespace whitespace <1> True True <1.2> True True <1.2.3> False False <-6> True True <1/2> True True <12e> False False <B17> False False <1.3e+12> True True <1.3e12> True True <-2.6e-3> True True <zero> False False <0x> False False <0xA10> True True <0b1001> True True <0o16> True True <0o18> False False <2+5i> True True <True> False False <False> False False <Inf> True True <NaN> True True <0x10.50> True True <0b102> False False <0o_5_3> True True <௫௯> True True < 12 > True True <1 1 1> False False <> True False < > True False
isnumeric $Typecheck onDefint FALSE, TRUEFALSE = 0TRUE = NOT FALSEFunction isNumeric(s as string, optchar as string) as integer If len(s) = 0 then Result = FALSE Exit Function End If if instr(s,"+") > 1 then Result = FALSE exit function end if if instr(s,"-") > 1 then Result = FALSE exit function end if Defint i, ndex = 0 For i = 1 to len(s) select case asc(mid$(s,i,1)) case 43 '+ case 45 '- case 46 '. if ndex = 1 then Result = FALSE Exit function end if ndex = 1 case 48 to 57 '0 to 9 case else if instr(optchar,(mid$(s,i,1))) = 0 then Result = FALSE exit function end if end select next Result = TRUEEnd Function '============================================================'Begin'============================================================showmessage (str$(isNumeric("-152.34","")))endRebol [Title: "Is Numeric?"URL: http://rosettacode.org/wiki/IsNumeric]; Built-in.numeric?: func [x][decimal? try [to decimal! x]]; Parse dialect for numbers.pnumeric?: function/with [x][ parse x number][ sign: [0 1 [#"-" | #"+"]] digit: charset "0123456789" int: [some digit] float: [int "." int] number: [ sign float ["e" | "E"] sign int | sign int ["e" | "E"] sign int | sign float | sign int ]]; Test cases.valid: [ "10" "-99" "10.43" "-12.04" "1e99" "1.0e10" "-10e3" "-9.12e7" "2e-4" "-3.4E-5"]invalid: [ "3phase" "Garkenhammer" "e" "n3v3r" "phase3"]print "^/Valid cases:"foreach x valid [print [mold x numeric? x pnumeric? x]]print "^/Invalid cases:"foreach x invalid [print [mold x numeric? x pnumeric? x]]
Valid cases:"10" true true"-99" true true"10.43" true true"-12.04" true true"1e99" true true"1.0e10" true true"-10e3" true true"-9.12e7" true true"2e-4" true true"-3.4E-5" true trueInvalid cases:"3phase" false false"Garkenhammer" false false"e" false false"n3v3r" false false"phase3" false false
Retro does not have floating point numbers as part of the core system. For others, this can be done with:
'123 a:from-string TRUE [ swap c:digit? and ] a:reduce
/*REXX program determines if a string is numeric, using REXX's rules for numbers. */yyy=' -123.78' /*or some such. */ /*strings below are all numeric (REXX).*/zzz= ' -123.78 'zzz= '-123.78'zzz= '2'zzz= "2"zzz= 2zzz= '000000000004'zzz= '+5'zzz= +5zzz= ' +6 'zzz= ' + 7 'zzz= ' - 8 'zzz= ' - .9'zzz= '- 19.'zzz= '.7'zzz= .7zzz= '2e3'zzz= 47e567zzz= '2e-3'zzz= '1.2e1'zzz= ' .2E6'zzz= ' 2.e5 'zzz= ' +1.2E0002 'zzz= ' +1.2e+002 'zzz= ' +0000001.200e+002 'zzz= ' - 000001.200e+002 'zzz= ' - 000008.201e-00000000000000002 ' /*Note: some REXX interpreters allow use of tab chars as blanks. */ /*all statements below are equivalent.*/if \datatype(yyy, 'n') then say 'oops, not numeric:' yyyif \datatype(yyy, 'N') then say 'oops, not numeric:' yyyif ¬datatype(yyy, 'N') then say 'oops, not numeric:' yyyif ¬datatype(yyy, 'numeric') then say 'oops, not numeric:' yyyif ¬datatype(yyy, 'nimrod.') then say 'oops, not numeric:' yyyif datatype(yyy) \== 'NUM' then say 'oops, not numeric:' yyyif datatype(yyy) /== 'NUM' then say 'oops, not numeric:' yyyif datatype(yyy) ¬== 'NUM' then say 'oops, not numeric:' yyyif datatype(yyy) ¬= 'NUM' then say 'oops, not numeric:' yyy /*note: REXX only looks at the first char for DATATYPE's 2nd argument.*/ /*note: some REXX interpreters don't support the ¬ (not) character. */
see isdigit("0123456789") + nl + # print 1 isdigit("0123a") # print 0for Raspberry pi pico 2 see instructions to page risc v
# riscv assembly raspberry pico2 rp2350# program verifnumber.s# connexion putty com3/*********************************************//* CONSTANTES *//********************************************//* for this file see risc-v task include a file */.include "../../../constantesRiscv.inc".equ BUFFSIZE, 200/****************************************************//* MACROS *//****************************************************/#.include "../ficmacrosriscv.inc" # only for debugging/*******************************************//* INITIALED DATAS *//*******************************************/ .dataszMessStart: .asciz "Program riscv start.\r\n"szMessEndOk: .asciz "Program riscv end OK.\r\n"szCariageReturn: .asciz "\r\n"szMessNum: .asciz "Enter number : \n"szMessError: .asciz "String is not a number !!!\n"szMessInteger: .asciz "String is a integer.\n"szMessFloat: .asciz "String is a float.\n"szMessFloatExp: .asciz "String is a float with exposant.\n"szMessErreurBuf: .asciz "Buffer size error.".align 2/*******************************************/ /* UNINITIALED DATA *//*******************************************/ .bsssBuffer: .skip BUFFSIZE.align 2/**********************************************//* SECTION CODE *//**********************************************/.text.global mainmain: call stdio_init_all # général init1: # start loop connexion li a0,0 # raz argument register call tud_cdc_n_connected # waiting for USB connection beqz a0,1b # return code = zero ? yes -> loop la a0,szMessStart # message address call writeString # display message2: # loop begin la a0,szMessNumcall writeString la a0,sBufferli a1,BUFFSIZEcall readString # entry stringla t0,sBufferadd t1,t0,a0sb x0,(t1) la a0,sBuffer call controlNumber # control beqz a0,5fli t0,1bne a0,t0,3fla a0,szMessInteger call writeStringj 6f3:li t0,2bne a0,t0,4fla a0,szMessFloat call writeStringj 6f4:li t0,3bne a0,t0,5fla a0,szMessFloatExpcall writeStringj 6f5: la a0,szMessErrorcall writeString6:j 2b # and loop la a0,szMessEndOk # message address call writeString # display message call getchar100: # final loop j 100b/**************************************************//* saisie des commandes *//**************************************************//* a0 buffer address *//* a1 buffer size */readString: # INFO: readString addi sp, sp, -16 sw ra, 0(sp) sw s0, 4(sp) sw s1, 8(sp) sw s2, 12(sp) mv s0,a0 # buffer address li s1,0 mv s2,a1 # buffer size1: li a0,100 call getchar # character read beq a0,x0,2f # zero ? li a1,0xD # return carriage beq a0,a1,2f add t1,s0,s1 # compute address buffer sb a0,(t1) # store character in buffer addi s1,s1,1 # increment indice bge s1,s2,99f call putchar # write charactere for display in host j 1b # and loop 2: add s1,s0,s1 sb x0,(s1) # zero final li a0,0xA call putchar li a0,0xD call putcharmv a0,s0 j 100f99: # error la a0,szMessErreurBuf call writeString li a0,-1100: lw ra, 0(sp) lw s0, 4(sp) lw s1, 8(sp) lw s2, 12(sp) addi sp, sp, 16 ret/******************************************************************//* control if string is number */ /******************************************************************//* a0 contains the address of the string *//* a0 return 0 if not a number *//* a0 return 1 if integer eq 12345 or -12345 *//* a0 return 2 if float eq 123.45 or 123,45 or -123,45 *//* a0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 or +123,45e+30 */controlNumber: addi sp, sp, -4 sw ra, 0(sp) li t1,0 # string indice li t3,0 # point or comma counter li t5,' '2: add t4,a0,t1lbu t2,(t4)beqz t2,9f # if end -> errorbne t2,t5,3faddi t1,t1,1 # suppress spacesj 2b3: li t5,'-' bne t2,t5,4f addi t1,t1,1 # negativej 5f4:li t5,'+' bne t2,t5,5f addi t1,t1,1 # positive5: add t4,a0,t1lbu t2,(t4)beqz t2,9f # end ?bne t2,t5,6faddi t1,t1,1 # suppress spacej 5b6: add t4,a0,t1lbu t2,(t4)beqz t2,19f # end ?li t5,'E' # exposant ?beq t2,t5,10fli t5,'e' # exposant ?beq t2,t5,10fli t5,'.' # point ?bne t2,t5,7faddi t3,t3,1 # yes increment counteraddi t1,t1,1 j 6b # and loop7:li t5,',' # comma ?bne t2,t5,8faddi t3,t3,1 # yes increment counteraddi t1,t1,1 j 6b # and loop8:li t5,'0' # control digit < 0blt t2,t5,9fli t5,'9' # control digit > 9bgt t2,t5,9faddi t1,t1,1 # no errorj 6b # and loop 9: # error detected li a0,0 j 100f10: # float with exposant addi t1,t1,1 add t4,a0,t1lbu t2,(t4)bnez t2,11f li a0,0 # end -> error j 100f11: li t5,'-' bne t2,t5,12faddi t1,t1,1 # negative exposantj 13f12: li t5,'+' bne t2,t5,13faddi t1,t1,1 # positive exposant13: li t6,0 # digit counter14: add t4,a0,t1lbu t2,(t4)beqz t2,16f # endli t5,'0' # control digit < 0blt t2,t5,15fli t5,'9' # control digit > 9bgt t2,t5,15f addi t1,t1,1 addi t6,t6,1 # increment counter digit j 14b # and loop15: # error li a0,0j 100f 16: bnez t6,17f li a0,0 # number digit exposant = 0 -> error j 100f 17: li t5,2 ble t6,t5,18f # number digit exposant > 2 -> error li a0,0j 100f 18: li a0,3 # valid float with exposant j 100f 19: bnez t3,20fli a0,1 # valid integerj 100f20: li t5,1 bne t3,t5,21f # number of point or comma = 1 ?li a0,2 # valid floatj 100f21:li a0,0 # error100: lw ra, 0(sp) addi sp, sp, 4 ret/************************************//* file include Fonctions *//***********************************//* for this file see risc-v task include a file */.include "../../../includeFunctions.s"
Program riscv start.Enter number :123String is a integer.Enter number :-345String is a integer.Enter number :4,5String is a float.Enter number :5,abString is not a number !!!Enter number :-45E56String is a float with exposant.Enter number :+12e-5String is a float with exposant.Enter number :
This one-liner returns 1 if the string is either a real number, a complex number or a binary integer - and zero otherwise.
≪IFERR STR→THEN DROP 0ELSE TYPE { 0 1 10 } SWAP POS SIGNEND ≫ ‘NUM?’ STOdef is_numeric?(s) begin Float(s) rescue false # not numeric else true # numeric endend
or more compact:
def is_numeric?(s) !!Float(s) rescue falseend
NB! Since Ruby 2.6 you no longer need `rescue`:
def is_numeric?(s) !!Float(s, exception: false)end
Adding `exception: false` will make it return `nil` instead.
sample
strings = %w(0 0.0 -123 abc 0x10 0xABC 123a -123e3 0.1E-5 50e)strings.each do |str| puts "%9p => %s" % [str, is_numeric?(str)]end
"0" => true "0.0" => true "-123" => true "abc" => false "0x10" => true "0xABC" => true "123a" => false "-123e3" => true "0.1E-5" => true "50e" => false
print isNumeric("123") print isNumeric("1ab")' ------------------------' Numeric Check' 0 = bad' 1 = good' ------------------------FUNCTION isNumeric(f$)isNumeric = 1f$= trim$(f$)if left$(f$,1) = "-" or left$(f$,1) = "+" then f$ = mid$(f$,2)for i = 1 to len(f$) d$ = mid$(f$,i,1)if d$ = "," then goto [nxtDigit]if d$ = "." then if dot$ = "." then isNumeric = 0dot$= "."goto [nxtDigit]end if if (d$ < "0") or (d$ > "9") then isNumeric = 0[nxtDigit]next iEND FUNCTION123 11ab 0
// This function is not limited to just numeric types but rather anything that implements the FromStr trait.fn parsable<T: FromStr>(s: &str) -> bool { s.parse::<T>().is_ok()}Sample code:
use std::str::FromStr;fn parsable<T: FromStr>(s: &str) -> bool { s.parse::<T>().is_ok()}fn main() { let test_cases = [ "142857", "3.14", "not of this earth!" ]; let types: &[(&str, fn(&str) -> bool)] = &[ ("i32", parsable::<i32> as fn(&str) -> bool), ("i64", parsable::<i32> as fn(&str) -> bool), ("i128", parsable::<i32> as fn(&str) -> bool), ("f64", parsable::<f64> as fn(&str) -> bool), ]; println!(""); for &case in &test_cases { for &(type_name, parse_fn) in types { println!( "'{}' {} be parsed as {}", case, if parse_fn(case) { "can" } else { "_cannot_" }, type_name ); } println!(""); }}'142857' can be parsed as i32'142857' can be parsed as i64'142857' can be parsed as i128'142857' can be parsed as f64'3.14' _cannot_ be parsed as i32'3.14' _cannot_ be parsed as i64'3.14' _cannot_ be parsed as i128'3.14' can be parsed as f64'not of this earth!' _cannot_ be parsed as i32'not of this earth!' _cannot_ be parsed as i64'not of this earth!' _cannot_ be parsed as i128'not of this earth!' _cannot_ be parsed as f64
import scala.util.control.Exception.allCatchdef isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
def isNumeric(input: String): Boolean = input.forall(_.isDigit)
Or a more complete version, using a complex regular expression:
def isNumeric2(str: String): Boolean = { str.matches(s"""[+-]?((\d+(e\d+)?[lL]?)|(((\d+(\.\d*)?)|(\.\d+))(e\d+)?[fF]?))""")}Or using the built-in number parsing and catching exceptions:
def isNumeric(str: String): Boolean = { !throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble)} def throwsNumberFormatException(f: => Any): Boolean = { try { f; false } catch { case e: NumberFormatException => true }}string->number returns #f when the string is not numeric and otherwise the number, which is non-#f and therefore true.
(define (numeric? s) (string->number s))
The function isNumeric uses the functiongetNumber from the libraryscanstri.s7i.GetNumber reads a numeric literal from a string. The numeric literal is removed from the input string.
$ include "seed7_05.s7i"; include "scanstri.s7i";const func boolean: isNumeric (in var string: stri) is func result var boolean: isNumeric is FALSE; local var string: numberStri is ""; begin numberStri := getNumber(stri); isNumeric := stri = ""; end func;
There is the theString.looks_like_number method, which returns true when a given strings looks like a number:
say "0.1E-5".looks_like_number; #=> true
Alternatively, we can use regular expressions to determine this:
func is_numeric(s) { (s ~~ /^[+-]?+(?=\.?[0-9])[0-9_]*+(?:\.[0-9_]++)?(?:[Ee](?:[+-]?+[0-9_]+))?\z/) || (s ~~ /^0(?:b[10_]*|x[0-9A-Fa-f_]*|[0-9_]+\b)\z/)}Sample:
var strings = %w(0 0.0 -123 abc 0x10 0xABC 123a -123e3 0.1E-5 50e);for str in strings { say ("%9s => %s" % (str, is_numeric(str)))}0 => true 0.0 => true -123 => true abc => false 0x10 => true 0xABC => true 123a => false -123e3 => true 0.1E-5 => true 50e => false
Simula uses the '&' instead of 'e' or 'E' for the exponent part of a floating point decimal number.
BEGIN BOOLEAN PROCEDURE ISNUMERIC(W); TEXT W; BEGIN BOOLEAN PROCEDURE MORE; MORE := W.MORE; CHARACTER PROCEDURE NEXT; NEXT := IF MORE THEN W.GETCHAR ELSE CHAR(0); CHARACTER PROCEDURE LAST; LAST := IF W.LENGTH = 0 THEN CHAR(0) ELSE W.SUB(W.LENGTH,1).GETCHAR; CHARACTER CH; W.SETPOS(1); IF MORE THEN BEGIN CH := NEXT; IF CH = '-' OR CH = '+' THEN CH := NEXT; WHILE DIGIT(CH) DO CH := NEXT; IF CH = '.' THEN BEGIN CH := NEXT; IF NOT DIGIT(CH) THEN GOTO L; WHILE DIGIT(CH) DO CH := NEXT; END; IF CH = '&' THEN BEGIN CH := NEXT; IF CH = '-' OR CH = '+' THEN CH := NEXT; WHILE DIGIT(CH) DO CH := NEXT; END; END; L: ISNUMERIC := (W.LENGTH > 0) AND THEN (NOT MORE) AND THEN DIGIT(LAST); END; REAL X; TEXT T; FOR X := 0, -3.1415, 2.768&+31, 5&10, .5, 5.&10 DO BEGIN OUTREAL(X, 10, 20); OUTIMAGE; END; OUTIMAGE; FOR T :- "0", "-3.1415", "2.768&+31", ".5", "5&22" DO BEGIN OUTTEXT(IF ISNUMERIC(T) THEN " NUMERIC " ELSE "NOT NUMERIC "); OUTCHAR('"'); OUTTEXT(T); OUTCHAR('"'); IF T = "0" THEN OUTCHAR(CHAR(9)); OUTCHAR(CHAR(9)); COMMENT PROBE ; X := T.GETREAL; OUTREAL(X, 10, 20); OUTIMAGE; END; OUTIMAGE; X := 5.&10; !X := 5&; !X := 5.; X := .5; FOR T :- "", "5.", "5&", "5&+", "5.&", "5.&-", "5.&10" DO BEGIN OUTTEXT(IF ISNUMERIC(T) THEN " NUMERIC " ELSE "NOT NUMERIC "); OUTCHAR('"'); OUTTEXT(T); OUTCHAR('"'); OUTIMAGE; END;END0.000000000&+000 -3.141500000&+000 2.768000000&+031 5.000000000&+010 5.000000000&-001 5.100000000&+000 NUMERIC "0" 0.000000000&+000 NUMERIC "-3.1415" -3.141500000&+000 NUMERIC "2.768&+31" 2.768000000&+031 NUMERIC ".5" 5.000000000&-001 NUMERIC "5&22" 5.000000000&+022NOT NUMERIC ""NOT NUMERIC "5."NOT NUMERIC "5&"NOT NUMERIC "5&+"NOT NUMERIC "5.&"NOT NUMERIC "5.&-"NOT NUMERIC "5.&10"
The String class has the methodisNumeric; this method (at least on version 3.0.4) does not recognize as number strings like '-123'! So I've written an extension...
String extend [ realIsNumeric [ (self first = $+) | (self first = $-) ifTrue: [ ^ (self allButFirst) isNumeric ] ifFalse: [ ^ self isNumeric ] ]]{ '1234'. "true" '3.14'. '+3.8111'. "true" '+45'. "true" '-3.78'. "true" '-3.78.23'. "false" '123e3' "false: the notation is not recognized"} do: [ :a | a realIsNumeric printNl ](should work with all)
(Number readFrom:(aString readStream) onError:[nil]) notNil
to handle radix numbers (such as 2r10111), use:
(Scanner scanNumberFrom:(aString readStream)) notNil
This task is easy in Snobol. Use the convert( ) function as a predicate returning success (T) or failure (F) for string to real conversion.
define('nchk(str)') :(nchk_end)nchk convert(str,'real') :s(return)f(freturn)nchk_end * # Wrapper for testing define('isnum(str)') :(isnum_end)isnum isnum = 'F'; isnum = nchk(str) 'T' isnum = isnum ': ' str :(return)isnum_end * # Test and display output = isnum('123') output = isnum('123.0') output = isnum('123.') output = isnum('-123') output = isnum('3.14159') output = isnum('1.2.3') output = isnum('abc') output = isnum('A440')endT: 123T: 123.0T: 123.T: -123T: 3.14159F: 1.2.3F: abcF: A440
declare @s varchar(10)set @s = '1234.56'print isnumeric(@s) --prints 1 if numeric, 0 if not.if isnumeric(@s)=1 begin print 'Numeric' end else print 'Non-numeric'
version 9.7 or higher.
With SQL PL:
--#SET TERMINATOR @CREATE OR REPLACE FUNCTION IS_NUMERIC ( IN STRING VARCHAR(10) ) RETURNS SMALLINT -- ) RETURNS BOOLEAN BEGIN DECLARE RET SMALLINT; -- DECLARE RET BOOLEAN; DECLARE TMP INTEGER; DECLARE CONTINUE HANDLER FOR SQLSTATE '22018' SET RET = 1; -- SET RET = FALSE; SET RET = 0; --SET RET = TRUE; SET TMP = INTEGER(STRING); RETURN RET; END @VALUES IS_NUMERIC('5')@VALUES IS_NUMERIC('0')@VALUES IS_NUMERIC('-1')@VALUES IS_NUMERIC('A')@VALUES IS_NUMERIC('-')@VALUES IS_NUMERIC('z')@VALUES IS_NUMERIC('')@VALUES IS_NUMERIC(' ')@Output:
db2 -td@db2 => BEGIN...db2 (cont.) => END @DB20000I The SQL command completed successfully.VALUES IS_NUMERIC('5')1 ------ 0 1 record(s) selected.VALUES IS_NUMERIC('0')1 ------ 0 1 record(s) selected.VALUES IS_NUMERIC('-1')1 ------ 0 1 record(s) selected.VALUES IS_NUMERIC('A')1 ------ 1 1 record(s) selected.VALUES IS_NUMERIC('-')1 ------ 1 1 record(s) selected.VALUES IS_NUMERIC('z')1 ------ 1 1 record(s) selected.VALUES IS_NUMERIC('')1 ------ 1 1 record(s) selected.VALUES IS_NUMERIC(' ')1 ------ 1 1 record(s) selected.(* this function only recognizes integers in decimal format *)fun isInteger s = case Int.scan StringCvt.DEC Substring.getc (Substring.full s) of SOME (_,subs) => Substring.isEmpty subs | NONE => falsefun isReal s = case Real.scan Substring.getc (Substring.full s) of SOME (_,subs) => Substring.isEmpty subs | NONE => falsefun isNumeric s = isInteger s orelse isReal s
func isNumeric(a: String) -> Bool { return Double(a) != nil}This one only checks whether it is an integer:
func isNumeric(a: String) -> Bool { return a.toInt() != nil}proc isNumeric {str} { string is double -strict $str}A more robust exception-based example:
# will output an error message# and quitproc fatal {msg} { puts stderr "$msg" exit 1}# a bad stringset x 174gg.4 try { set n [expr {double($x)}] set n [expr {int($x)}] puts $x } on error { error options } { fatal "$::errorInfo" }expected floating-point number but got "174gg.4" while executing"expr {double($x)}" ("try" body line 2)Unix TMG dialect. NOTE: the program also performs some basic normalization (namely, removing the plus sign and translating "E" to "e"):
prog: ignore(<< >>) parse(line)\prog parse(error)\prog;line: number *;number: ignore(none) sign float (exp | ={}) = { < True: > 3 2 1 * };sign: <+>={} | <->={<->} | ={};float: int ( <.> decim = { 2 <.> 1 } | = { 1 } ) | <.> int = { <.> 1 };int: smark any(digit) string(digit) scopy;decim: smark string(digit) scopy;exp: any(<<eE>>) sign int = { <e> 2 1 };error: smark any(nonl) ignore(none) string(nonl) scopy * = { <False: > 1 * };digit: <<0123456789>>;none: <<>>;nonl: !<<>>;Sample input:
123+12345.678.6781.+1.0E+99-7.-123e-12300000.1.2.30x123a1-a51 000 0001,000,0001.00e1e1
Sample output:
True: 123 True: 12345.678 True: .678 True: 1. True: 1.0e99 True: -7. True: -123e-123 True: 00000False: .False: 1.2.3False: 0x123False: a1-a5False: 1 000 000False: 1,000,000False: 1.00e1e1
Returns a flag of TRUE if character-string parameter represents a signed or unsigned integer. Otherwise returns a flag of FALSE. The success or failure is dependent on the source is valid in the current numeric base. The>number function also recognizes several optional prefixes for overriding the current base during conversion.
[ ( string -- flag ) >number nip ] is isNumeric( Some tests )decimal" 100" isNumeric . ( succeeds, 100 is a valid decimal integer )" 100.21" isNumeric . ( fails, 100.21 is not an integer)" a" isNumeric . ( fails, 'a' is not a valid integer in the decimal base )" $a" isNumeric . ( succeeds, because $ is a valid override prefix ) ( denoting that the following character is a hexadecimal number )
DECLARE FUNCTION isnumeric$LET true$ = "True"LET false$ = "False"LET s$ = "-152.34"PRINT s$, " => "; isnumeric$(s$)LET s$ = "1234.056789"PRINT s$, " => "; isnumeric$(s$)LET s$ = "1234.56"PRINT s$, " => "; isnumeric$(s$)LET s$ = "021101"PRINT s$, " => "; isnumeric$(s$)LET s$ = "Dog"PRINT s$, " => "; isnumeric$(s$)LET s$ = "Bad125"PRINT s$, " => "; isnumeric$(s$)LET s$ = "-0177"PRINT s$, " => "; isnumeric$(s$)LET s$ = "+123abcd.ef"PRINT s$, " => "; isnumeric$(s$)LET s$ = "54321"PRINT s$, " => "; isnumeric$(s$)LET s$ = "123xyz"PRINT s$, " => "; isnumeric$(s$)LET s$ = "xyz"PRINT s$, " => "; isnumeric$(s$)FUNCTION isnumeric$(s$) LET optchar$ = "" IF len(s$) = 0 then LET isnumeric$ = false$ EXIT FUNCTION END IF IF pos(s$,"+") > 1 then LET isnumeric$ = false$ EXIT FUNCTION END IF IF pos(s$,"-") > 1 then LET isnumeric$ = false$ EXIT FUNCTION END IF LET ndex = 0 FOR i = 1 to len(s$) SELECT CASE ord((s$)[i:i+1-1][1:1]) CASE 43 !+ CASE 45 !- CASE 46 !. IF ndex = 1 then LET isnumeric$ = false$ EXIT FUNCTION END IF LET ndex = 1 CASE 48 to 57 !0 a 9 CASE else IF pos(optchar$,((s$)[i:i+1-1])) = 0 then LET isnumeric$ = false$ EXIT FUNCTION END IF END SELECT NEXT i LET isnumeric$ = true$END FUNCTIONEND
IsNum ← ¬≍"I"⍣(⋕)("I")shorter:
IsNum ← ¬type⍣⋕
#!/bin/bashisnum() { printf "%f" $1 >/dev/null 2>&1}check() { if isnum $1 then echo "$1 is numeric" else echo "$1 is NOT numeric" fi}check 2check -3check +45.44check -33.332check 33.aacheck 3.3.32 is numeric-3 is numeric+45.44 is numeric-33.332 is numeric33.aa is NOT numeric3.3.3 is NOT numeric
def isnum (string str)trydouble strreturn truecatch valueerrorreturn falseend tryend isnum
In France, IsNumeric("123.45") return False.So we have to check the "." or "," and replace it by the Application.DecimalSeparator.
Sub Main() Debug.Print Is_Numeric("") Debug.Print Is_Numeric("-5.32") Debug.Print Is_Numeric("-51,321 32") Debug.Print Is_Numeric("123.4") Debug.Print Is_Numeric("123,4") Debug.Print Is_Numeric("123;4") Debug.Print Is_Numeric("123.4x")End SubPrivate Function Is_Numeric(s As String) As BooleanDim Separat As String, Other As String Separat = Application.DecimalSeparator Other = IIf(Separat = ",", ".", ",") Is_Numeric = IsNumeric(Replace(s, Other, Separat))End FunctionIsNumeric(Expr)
Returns a True if numeric and a false if not.
This routine returns TRUE if there is numeric value at current cursor location.Only signed and unsigned integers are recognized, in decimal, hex (preceded with 0x) or octal (preceded with 0o).Remove the SUPPRESS option to evaluate an expression instead of single numeric value.
:IS_NUMERIC:if (Num_Eval(SUPPRESS)==0 && Cur_Char != '0') { Return(FALSE)} else { Return(TRUE)}Dim Value As String = "+123"If IsNumeric(Value) Then PRINT "It is numeric."End If
import strconvfn is_numeric(s string) bool {strconv.atof64(s) or {return false}return true}fn main() { println("Are these strings numeric?") strings := ["1", "3.14", "-100", "1e2", "NaN", "rose", "0xff", "0b110"] for s in strings { println(" ${s:4} -> ${is_numeric(s)}") }}Are these strings numeric? 1 -> true 3.14 -> true -100 -> true 1e2 -> true NaN -> false rose -> false 0xff -> true 0b110 -> true
Wren's Num class already has a static method which does what this task requires.
import "./fmt" for FmtSystem.print("Are these strings numeric?")for (s in ["1", "3.14", "-100", "1e2", "NaN", "0xaf", "rose"]) { var i = Num.fromString(s) // returns null if 's' is not numeric System.print(" %(Fmt.s(4, s)) -> %((i != null) ? "yes" : "no")")}Are these strings numeric? 1 -> yes 3.14 -> yes -100 -> yes 1e2 -> yes NaN -> yes 0xaf -> yes rose -> no
The inbuilt functionSTRING->NUMBER returns the numeric value of a string if it can. We discard this value and return the Boolean value 'true'; otherwise, theIF conditional will not be satisfied and will return 'false'.
(DEFUN NUMERICP (X) (IF (STRING->NUMBER X) T))
The compiler is more strict in the characters it accepts as numeric thanwhat is accepted here. This program indicates more of what the inputintrinsics (IntIn, RlIn and HexIn) would accept as numeric.
string 0;func IsNumeric(Str);char Str;[while Str(0) # 0 do [if Str(0) >= ^0 and Str(0) <= ^9 then return true; if Str(0) = ^$ then [if Str(1) >= ^0 and Str(1) <= ^9 then return true; if Str(1) >= ^A and Str(1) <= ^F then return true; if Str(1) >= ^a and Str(1) <= ^f then return true; ]; Str:= Str+1; ];return false;];int Strs, S;[Text(0, "Are these strings numeric?^m^j");Strs:= ["1", "3.14", "-100", "1e2", "NaN", "$af", "%1_1011", "rose", ". 3", "num9", "x$ 9", "x$ a"];for S:= 0 to 12-1 do [Text(0, if IsNumeric(Strs(S)) then "yes : " else "no : "); Text(0, Strs(S)); CrLf(0); ];]
Are these strings numeric?yes : 1yes : 3.14yes : -100yes : 1e2no : NaNyes : $afyes : %1_1011no : roseyes : . 3yes : num9yes : x$ 9no : x$ a
Use the /S8 switch on the ZSM4 assembler for 8 significant characters for labels and names
;; Check if input string is a number using Z80 assembly language;; Runs under CP/M 3.1 on YAZE-AG-2.51.2 Z80 emulator; Assembled with zsm4 on same emulator/OS, uses macro capabilities of said assembler; Created with vim under Windows;; 2023-04-04 Xorph;;; Useful definitions;bdosequ 05h; Call to CP/M BDOS functionstrdelequ 6eh; Set string delimiterreadstrequ 0ah; Read string from consolewrtstrequ 09h; Write string to consolenulequ 00h; ASCII control charactersescequ 1bhcrequ 0dhlfequ 0ahcnullequ '0'; ASCII character constantscnineequ '9'cminusequ '-'cdotequ '.'buflenequ 30h; Length of input bufferminbitequ 00h; Bit 0 is used as flag for '-'dotbitequ 01h; Bit 1 is used as flag for '.';; Macros for BDOS calls;setdel macrochar; Set string delimiter to charldc,strdellde,charcallbdosendmprint macromsg; Output string to consoleldc,wrtstrldde,msgcallbdosendmnewlinemacro; Print newlineldc,wrtstrldde,crlfcallbdosendmreadln macrobuf; Read a line from inputldc,readstrldde,bufcallbdosendm;; =====================; Start of main program; =====================;csegisnum:setdelnul; Set string terminator to nul ('\0') - '$' is default in CP/Mprinthelpnewlinenewlinereadnum:ldb,buflen; Clear input bufferldhl,bufcontclrloop:ld(hl),0inchldjnzclrloopreadlninputbuf; Read a line from inputnewline; Newline is discarded during input, so write one...lda,(inputbuf+1); Length of actual inputcp0; If empty input, quitretzldb,a; Loop counter for djnz instructionldc,0; Use c for flags: '-' and '.' may be encountered at most once, '-' only at startldhl,bufcont; Start of actual inputloop:lda,(hl); Get next character into acpcminus; Check minus signjrz,chkminuscpcdot; Check dotjrz,chkdotcpcnull; Check if below '0'jrc,notanumcpcnine+1; Check if above '9'jrnc,notanumchecknxt:setminbit,c; Whatever the case, no more '-' are allowed after the first characterinchl; Increase hl to next character and repeat until donedjnzloopprintbufcont; If we made it this far, we are done and the string is numericprintyesmsgnewlinenewlinedone:jpreadnum; Read next input from user until terminated with ^C or empty inputret; Return to CP/M (unreachable code)notanum:printbufcont; Print failure messageprintnomsgnewlinenewlinejrdonechkminus:bitminbit,c; If a '-' is encountered and the flag is already set, the string is not numericjrnz,notanumsetminbit,c; Otherwise, set flag and check next characterjrchecknxtchkdot:bitdotbit,c; If a '.' is encountered and the flag is already set, the string is not numericjrnz,notanumsetdotbit,c; Otherwise, set flag and check next characterjrchecknxt;; ===================; End of main program; ===================;;; ================; Data definitions; ================;dseghelp:defz'Enter numbers to check, end with empty line or ^C'inputbuf:; Input buffer for CP/M BDOS calldefbbuflen; Maximum possible lengthdefb00h; Returned length of actual inputbufcont:defsbuflen; Actual input areadefbnul; Null terminator for output, if buffer is filled completelyyesmsg:defz' is numeric'nomsg:defz' is not numeric'crlf:defbcr,lf,nul; Generic newlineE>isnumEnter numbers to check, end with empty line or ^C12341234 is numerichellohello is not numeric12.3412.34 is numeric-98.76-98.76 is numeric4.6.764.6.76 is not numeric34-56-2334-56-23 is not numeric-.9876543210-.9876543210 is numeric444555.444555. is numeric1234c1234c is not numeric123e45123e45 is not numeric
const std = @import("std");const stdout = std.io.getStdOut().writer();fn isNumeric(str: []const u8) bool { const num = std.mem.trim(u8, str, "\x20"); _ = std.fmt.parseFloat(f64, num) catch return false; return true;}pub fn main() !void { const s1 = " 123"; const s2 = " +123"; const s3 = " 12.3"; const s4 = "-12.3"; const s5 = "12e-3"; const s6 = "=12-3"; const s7 = "abcde"; const s8 = "12cde"; const s9 = "NaN"; const s10 = "0xFF"; try stdout.print("Is {s} numeric? {}\n", .{ s1, isNumeric(s1) }); try stdout.print("Is {s} numeric? {}\n", .{ s2, isNumeric(s2) }); try stdout.print("Is {s} numeric? {}\n", .{ s3, isNumeric(s3) }); try stdout.print("Is {s} numeric? {}\n", .{ s4, isNumeric(s4) }); try stdout.print("Is {s} numeric? {}\n", .{ s5, isNumeric(s5) }); try stdout.print("Is {s} numeric? {}\n", .{ s6, isNumeric(s6) }); try stdout.print("Is {s} numeric? {}\n", .{ s7, isNumeric(s7) }); try stdout.print("Is {s} numeric? {}\n", .{ s8, isNumeric(s8) }); try stdout.print("Is {s} numeric? {}\n", .{ s9, isNumeric(s9) }); try stdout.print("Is {s} numeric? {}\n", .{ s10, isNumeric(s10) });}Is 123 numeric? trueIs +123 numeric? trueIs 12.3 numeric? trueIs -12.3 numeric? trueIs 12e-3 numeric? trueIs =12-3 numeric? falseIs abcde numeric? falseIs 12cde numeric? falseIs NaN numeric? trueIs 0xFF numeric? true
fcn isNum(text){ try{ text.toInt(); True } catch{ try{ text.toFloat(); True } catch{ False } }}isNum("123.4") //-->TrueisNum("123") //-->TrueisNum("-123.4") //-->TrueisNum("123.4x") //-->FalseisNum("hoho") //-->FalseisNum(123.4) //-->TrueisNum(123) //-->Trueprogram: numeric case: 1 input: '1' output: true case: 2 input: '-3' output: true case: 3 input: '22.7' output: true case: 4 input: 'a' output: false case: 5 input: 'Fred' output: false case: 6 input: '' output: false