Determine if a string is numeric: Difference between revisions

added C translation to C++
(added C translation to C++)
 
(228 intermediate revisions by more than 100 users not shown)
Line 1:
{{task|Text processing}}
[[Category:Simple]]
 
;Task:
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.
 
 
{{Template:Strings}}
<br><br>
=={{header|6502 Assembly}}==
For this program, a valid numeric string literal consists of only numbers (ascii $30-$39), up to one <i>leading</i> minus sign, and no more than one decimal point. Anything else, including the null string, is considered non-numeric.
 
Macros used (VASM syntax):
<pre>
 
macro loadpair,regs,addr
lda #<\addr
sta \regs
lda #>\addr
sta \regs+1
endm
 
macro pushY
tya
pha
endm
 
macro popY
pla
tay
endm
</pre>
The code:
<syntaxhighlight lang="6502asm">*=$0801
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00 ;required init code on commodore 64 floppy disks
*=$0810
 
lda #$0e
jsr chrout ;required for my printing routine to work.
 
z_HL equ $02
z_L equ $02
z_H equ $03
z_B equ $04
loadpair z_HL,TestString0
jsr isStringNumeric
loadpair z_HL,TestString1
jsr isStringNumeric
loadpair z_HL,TestString2
jsr isStringNumeric
loadpair z_HL,TestString3
jsr isStringNumeric
 
loadpair z_HL,TestString4
jsr isStringNumeric
loadpair z_HL,TestString5
jsr isStringNumeric
loadpair z_HL,TestString6
jsr isStringNumeric
loadpair z_HL,TestString7
jsr isStringNumeric
loadpair z_HL,TestString8
jsr isStringNumeric
rts ;return to basic
 
isStringNumeric:
; input: z_HL = source address
pushY
ldy #0
sty z_B ;our tally for decimal points
checkFirstChar:
lda (z_HL),y
beq notNumeric ;a null string is not a valid number!
cmp #'-'
beq isNegative_OK
cmp #'.'
beq isFloat_OK
and #$30
cmp #$30
beq isNumeral_OK
;else, is not numeric
notNumeric:
popY
jsr PrintString_TextScreen ;prints what's already in z_HL
jsr NewLine
loadpair z_HL,isStringNumeric_Fail
jsr PrintString_TextScreen
jsr NewLine
jmp NewLine
;rts
isNegative_OK:
isNumeral_OK:
iny
jmp loop_isStringNumeric
isFloat_OK:
iny
inc z_B
loop_isStringNumeric:
lda (z_HL),y
beq Terminated_isStringNumeric
cmp #'.'
beq CheckIfDecimalAlreadyOccurred
and #$30
cmp #$30
bne notNumeric
loop_overhead_isStringNumeric:
iny
jmp loop_isStringNumeric
CheckIfDecimalAlreadyOccurred:
lda z_B
bne notNumeric
inc z_B
jmp loop_overhead_isStringNumeric
Terminated_isStringNumeric:
;if we got this far the string is numeric.
popY
jsr PrintString_TextScreen ;prints what's already in z_HL
jsr NewLine
loadpair z_HL,isStringNumeric_Pass
jsr PrintString_TextScreen
jsr NewLine
jmp NewLine
;rts
isStringNumeric_Pass:
db "IS NUMERIC",0
isStringNumeric_Fail:
db "IS NOT NUMERIC",0
TestString0:
db 0
TestString1:
db "123",0
TestString2:
db "-30",0
TestString3:
db "123.45",0
TestString4:
db "-123.45",0
TestString5:
db "ABCDE",0
TestString6:
db "-34-5",0
TestString7:
db "1.000.000",0
TestString8:
db ".23456",0</syntaxhighlight>
 
{{out}}
<pre>
ready.
load"*",8,1:
 
searching for *
loading
ready.
run
 
IS NOT NUMERIC
 
123
IS NUMERIC
 
-30
IS NUMERIC
 
123.45
IS NUMERIC
 
-123.45
IS NUMERIC
 
ABCDE
IS NOT NUMERIC
 
-34-5
IS NOT NUMERIC
 
1.000.000
IS NOT NUMERIC
 
.23456
IS NUMERIC
 
ready.
</pre>
 
=={{header|8th}}==
<syntaxhighlight lang="forth">: number? >n >kind ns:n n:= ;</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* 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 */
.data
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"
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 5f
1:
cmp x0,#1
bne 2f
ldr x0,qAdrszMessInteger // integer
bl affichageMess
b 5f
2:
cmp x0,#2
bne 3f
ldr x0,qAdrszMessFloat // float
bl affichageMess
b 5f
3:
cmp x0,#3
bne 5f
ldr x0,qAdrszMessFloatExp // float with exposant
bl affichageMess
5:
b loop
 
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform system call
qAdrszMessNum: .quad szMessNum
qAdrszMessError: .quad szMessError
qAdrszMessInteger: .quad szMessInteger
qAdrszMessFloat: .quad szMessFloat
qAdrszMessFloatExp: .quad szMessFloatExp
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsBuffer: .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 5f
4:
cmp x2,#'+' // positive ?
bne 5f
add x1,x1,#1
5:
ldrb w2,[x0,x1] // control space
cmp x2,#0 // end ?
beq 7f
cmp x2,#' ' // space ?
bne 6f
add x1,x1,#1
b 5b // loop
6:
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 loop
7:
cmp x2,#',' // comma ?
bne 8f
add x3,x3,#1 // yes increment counter
add x1,x1,#1
b 6b // and loop
8:
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 6b
 
9: // 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,#1
10:
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 loop
 
13:
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 100f
14:
cmp x3,#0
bne 15f
mov x0,#1 // valid integer
b 100f
15:
cmp x3,#1 // number of point or comma = 1 ?
blt 100f
bgt 99f // error
mov x0,#2 // valid float
b 100f
99:
mov x0,#0 // error
100:
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"
 
</syntaxhighlight>
 
=={{header|Action!}}==
 
=== Using string <-> number conversion ===
The solution below uses conversion string to number and number to string to determine if the string is numeric.
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
BYTE 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
OD
RETURN (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)
FI
RETURN (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.")
RETURN
 
PROC 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")
RETURN</syntaxhighlight>
 
=== Using a finite-state machine ===
The solution below uses a finite-state machine to determine if a string is numeric.
<syntaxhighlight lang="action!">BYTE FUNC IsSign(CHAR c)
IF c='- OR c='+ THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC IsDigit(CHAR c)
IF c>='0 AND c<='9 THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC IsDot(CHAR c)
IF c='. THEN
RETURN (1)
FI
RETURN (0)
 
BYTE FUNC IsExpSymbol(CHAR c)
IF c='E OR c='e THEN
RETURN (1)
FI
RETURN (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)
FI
RETURN (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.")
RETURN
 
PROC Main()
Test("56233")
Test("-315")
Test("1.36")
Test("-5.126")
Test("3.7E-05")
Test("1.23BC")
Test("5.6.3")
RETURN</syntaxhighlight>
 
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_is_numeric_state_machine.png Screenshot from Atari 8-bit computer]
<pre>
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.
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function isNumeric(num:String):Boolean
{
return !isNaN(parseInt(num));
}</langsyntaxhighlight>
 
=={{header|Ada}}==
The first file is the package interface containing the declaration of the Is_Numeric function.
<langsyntaxhighlight lang="ada">package Numeric_Tests is
function Is_Numeric (Item : in String) return Boolean;
end Numeric_Tests;</langsyntaxhighlight>
The second file is the package body containing the implementation of the Is_Numeric function.
<langsyntaxhighlight lang="ada">package body Numeric_Tests is
function Is_Numeric (Item : in String) return Boolean is
Dummy : Float;
Line 24 ⟶ 657:
return False;
end Is_Numeric;
end Numeric_Tests;</langsyntaxhighlight>
The last file shows how the Is_Numeric function can be called.
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Numeric_Tests; use Numeric_Tests;
 
Line 37 ⟶ 670:
Put_Line(S2 & " results in " & Boolean'Image(Is_Numeric(S2)));
Put_Line(S3 & " results in " & Boolean'Image(Is_Numeric(S3)));
end Is_Numeric_Test;</langsyntaxhighlight>
{{out}}
The output of the program above is:
<pre>
152 results in TRUE
-3.1415926 results in TRUE
Foo123 results in FALSE
</pre>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">integer
is_numeric(text s)
{
return !trap_q(alpha, s, 0);
}
 
integer
main(void)
{
if (!is_numeric("8192&*")) {
o_text("Not numeric.\n");
}
if (is_numeric("8192")) {
o_text("Numeric.\n");
}
 
return 0;
}</syntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 50 ⟶ 705:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">PROC is numeric = (REF STRING string) BOOL: (
BOOL out := TRUE;
PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE);
Line 76 ⟶ 731:
))
)
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
152 results in T
Line 83 ⟶ 738:
Foo123 results in F
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">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.</syntaxhighlight>
{{out}}
<pre>
" " 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
</pre>
 
=={{header|Apex}}==
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.
<syntaxhighlight lang="apex">
String numericString = '123456';
String partlyNumericString = '123DMS';
String decimalString = '123.456';
 
System.debug(numericString.isNumeric()); // this will be true
System.debug(partlyNumericString.isNumeric()); // this will be false
System.debug(decimalString.isNumeric()); // this will be false
System.debug(decimalString.remove('.').isNumeric()); // this will be true
</syntaxhighlight>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight lang="apl"> ⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123'
 
1 1 0</lang>
1 1 0</syntaxhighlight>
Works with more recent versions of <B>Dyalog APL</B><syntaxhighlight lang="apl"> ⊃⎕VFI '¯' @ ('-'∘=) '152 -3.1415926 Foo123' ⍝ Fast: replacement of - with APL high-minus required for ⎕VFI
1 1 0
⊃⎕VFI '-' ⎕R '¯' ⊣ '152 -3.1415926 Foo123' ⍝ Simple: (ditto)
1 1 0</syntaxhighlight>
 
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
{∧/⍵∊(⊃,¨'0123456789¯.+')}¨'152' '¯3.1415926' 'Foo123'
1 1 0
</syntaxhighlight>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
-- isNumString :: String -> Bool
on isNumString(s)
try
if class of s is string then
set c to class of (s as number)
c is real or c is integer
else
false
end if
on error
false
end try
end isNumString
 
 
 
-- TEST
on run
map(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}
end run
 
-- three :: () -> Int
script three
3
end script
 
-- four :: () -> Int
on four()
4
end four
 
 
-- GENERIC FUNCTIONS FOR TEST
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : f
end script
end if
end mReturn</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="applescript">{false, false, false, true, true, true, true, false, false, false}</syntaxhighlight>
 
The classic way's slightly simpler, since the coercion result ''must'' be a real or an integer if the coercion itself didn't error.
 
<syntaxhighlight lang="applescript">on isNumString(s)
if (s's class is not text) then return false
try
s as number
return true
on error
return false
end try
end isNumString</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* 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 */
.data
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"
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 5f
1:
cmp r0,#1
bne 2f
ldr r0,iAdrszMessInteger @ integer
bl affichageMess
b 5f
2:
cmp r0,#2
bne 3f
ldr r0,iAdrszMessFloat @ float
bl affichageMess
b 5f
3:
cmp r0,#3
bne 5f
ldr r0,iAdrszMessFloatExp @ float with exposant
bl affichageMess
5:
b loop
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessNum: .int szMessNum
iAdrszMessError: .int szMessError
iAdrszMessInteger: .int szMessInteger
iAdrszMessFloat: .int szMessFloat
iAdrszMessFloatExp: .int szMessFloatExp
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsBuffer: .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,#1
2:
ldrb r2,[r0,r1] @ control space
cmp r2,#0 @ end ?
beq 5f
cmp r2,#' '
addeq r1,#1
beq 2b
3:
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 3b
5: @ error detected
mov r0,#0
b 100f
6: @ 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 7b
8:
mov r0,#0
b 100f
9:
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 100f
10:
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 @ error
100:
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 @ return
 
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">print numeric? "hello world"
print numeric? "1234"
print numeric? "1234 hello world"
print numeric? "12.34"
print numeric? "!#@$"
print numeric? "-1.23"</syntaxhighlight>
{{out}}
 
<pre>false
true
false
true
false
true</pre>
 
=={{header|AutoHotkey}}==
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.
<langsyntaxhighlight lang="autohotkey">list = 0 .14 -5.2 ten 0xf
Loop, Parse, list, %A_Space%
MsgBox,% IsNumeric(A_LoopField)
Line 102 ⟶ 1,240:
}
 
;Output: 1 1 1 0 1</langsyntaxhighlight>
 
=={{header|AWK}}==
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:
<syntaxhighlight lang="awk">
<lang AWK>$ awk 'function isnum(x){return(x==x+0)}BEGIN{print isnum("hello"),isnum("-42")}'
$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'
0 1</lang>
</syntaxhighlight>
{{out}}
<pre>
0 1
</pre>
 
=={{header|BaCon}}==
<syntaxhighlight lang="bacon">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</syntaxhighlight>
{{out}}
<pre>
user@host $ ./isnumber
Your string: 12.3
This is a number
user@host $ ./isnumber
Your string: 12E3
This is a number
user@host $ ./isnumber
Your string: PI
Not a number
user@host $ ./isnumber
Your string: Hello
Not a number
</pre>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="qbasic">10 INPUT "Enter a string";S$:GOSUB 1000
20 IF R THEN PRINT "Is num" ELSE PRINT"Not num"
99 END
1000 T1=VAL(S$):T1$=STR$(T1)
1010 R=T1$=S$ OR T1$=" "+S$
1099 RETURN</langsyntaxhighlight>
 
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
#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" #binario
print s, " => "; isNumeric(s)
s = "0o177" #octal
print s, " => "; isNumeric(s)
s = "0xff" #hexadecimal
print s, " => "; isNumeric(s)
end
</syntaxhighlight>
{{out}}
<pre>
1234.056789 => 1
-2.567e7 => 1
Dog => 0
Bad125 => 0
-0177 => 1
0b1110 => 1
0o177 => 1
0xff => 0
</pre>
 
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="commodorebasic">5 print chr$(147);chr$(14)
10 input "Enter a string";s$:gosub 1000:print
20 if r then print "You entered a number.":goto 99
30 print "That is not a number."
99 end
1000 t1=val(s$):t1$=str$(t1)
1010 r=t1$=s$ or t1$=" "+s$
1099 return</syntaxhighlight>
 
{{out}}
<pre>Enter a string? 15893
 
You entered a number.
 
ready.
run
 
Enter a string? Llamas
 
That is not a number.
 
ready.
&#9608;</pre>
==={{header|QB64}}===
<syntaxhighlight lang="qb64">
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 If
Sleep
System
</syntaxhighlight>
{{out}}
<pre>
Enter a text or a number: 12345
You entered a number.
 
Enter a text or a number: Four
You did not enter a number.
 
Enter a text or a number: 99, rue de Rivoli
You did not enter a number.
 
Enter a text or a number: 9E4
You entered a number.</pre>
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.
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">set /a a=%arg%+0 >nul
if %a% == 0 (
if not "%arg%"=="0" (
echo Non Numeric.
) else (
echo Numeric.
)
) else (
echo Numeric.
)</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REPEAT
READ N$
IF FN_isanumber(N$) THEN
Line 138 ⟶ 1,417:
IF LEFT$(A$,1) = "0" THEN = TRUE
= FALSE
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>'PI' is NOT a number
'0123' is a number
Line 154 ⟶ 1,433:
'12+3' is NOT a number
'end' is NOT a number</pre>
 
=={{header|Befunge}}==
<syntaxhighlight lang="befunge"> ~:0\`#v_:"+"-!#v_:"-"-!#v_::"E"-\"e"-*#v_ v
v _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_v
v $_v# < < :#<
>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!v 0 > v
^ $< v < << ^_^#-"-"<
> "ciremuN">:#,_@ >>#$_"ciremun toN">:#,_@^ <</syntaxhighlight>
 
 
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.
 
{{out}}
<pre>
'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
</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">IsNumeric ← 1∘•ParseFloat⎊0</syntaxhighlight>
 
=={{header|Bracmat}}==
To check whether a string is a number, a fraction or an integer, use the patterns <code>#</code>, <code>/</code> and <code>~/#</code> ("not a fraction and yet a number"). In the pattern matching examples below (which can be typed in at the Bracmat prompt) <code>F</code> denotes 'failure' and <code>S</code> denotes 'success'.
 
<langsyntaxhighlight lang="bracmat">43257349578692:/
F
 
Line 167 ⟶ 1,486:
 
80000000000:~/#
S</langsyntaxhighlight>
Bracmat doesn't do floating point computations (historical reason: the Acorn Risc Machine a.k.a. ARM processor in the Archimedes computer did not have an FPU), but theThe pattern <code>~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)</code> recognises string representations of floating point numbers.
<langsyntaxhighlight lang="bracmat">@("1.000-4E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
F
 
Line 197 ⟶ 1,516:
 
@("0.0000":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S</langsyntaxhighlight>
 
Calculations 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.
To do computations with such "floating point strings" you would have to convert such strings to fractional representations first.
<lang bracmat>(float2fraction=
integerPart decimalPart d1 dn exp sign
. @( !arg
: ~/#?integerPart
( &0:?decimalPart:?d1:?dn
| "."
[?d1
(|? 0|`)
( &0:?decimalPart
| ~/#?decimalPart:>0
)
[?dn
)
( &0:?exp
| (E|e) ~/#?exp
)
)
& ( !integerPart*(-1:?sign):>0:?integerPart
| 1:?sign
)
& !sign*(!integerPart+!decimalPart*10^(!d1+-1*!dn))*10^!exp
);
 
=={{header|Burlesque}}==
( out$float2fraction$"1.2"
<syntaxhighlight lang="burlesque">
& out$float2fraction$"1.02"
ps^^-]to{"Int""Double"}\/~[\/L[1==?*
& out$float2fraction$"1.01"
</syntaxhighlight>
& out$float2fraction$"10.01"
 
& out$float2fraction$"10.01e10"
Assumes string is not empty.
& out$float2fraction$"10.01e1"
& out$float2fraction$"10.01e2"
& out$float2fraction$"10.01e-2"
& out$float2fraction$"-10.01e-2"
& out$float2fraction$"-10e-2"
& out$float2fraction$"0.000"
);
</lang>
Output:
<pre>6/5
51/50
101/100
1001/100
100100000000
1001/10
1001
1001/10000
-1001/10000
-1/10
0</pre>
 
=={{header|C}}==
Returns true (non-zero) if character-string parameter represents a signed or unsigned floating-point number. Otherwise returns false (zero).
 
<langsyntaxhighlight lang="c">#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
 
int isNumeric (const char * s)
bool isNumeric(const char *s) {
{
if (s == NULL || *s == '\0' || isspace(*s)) {
return 0false;
char * p;}
strtodchar (s, &*p);
strtod(s, &p);
return *p == '\0';
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
'''Framework:''' [[.NET]] 2.0+
 
<syntaxhighlight lang="csharp">public static bool IsNumeric(string s)
{
double Result;
return double.TryParse(s, out Result); // TryParse routines were added in Framework version 2.0.
}
 
string value = "123";
if (IsNumeric(value))
{
// do something
}</syntaxhighlight>
 
'''Framework:''' [[.NET]] 1.0+
 
<syntaxhighlight lang="csharp">public static bool IsNumeric(string s)
{
try
{
Double.Parse(s);
return true;
}
catch
{
return false;
}
}</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}<syntaxhighlight lang ="cpp">#include <sstreamcctype> // for istringstream
#include <cstdlib>
 
bool isNumeric(const char *s) {
if (s == nullptr || *s == '\0' || std::isspace(*s)) {
return false;
}
char *p;
std::strtod(s, &p);
return *p == '\0';
}</syntaxhighlight>
 
Using stringstream:
<syntaxhighlight lang="cpp">#include <sstream> // for istringstream
 
using namespace std;
Line 292 ⟶ 1,615:
return ( iss.rdbuf()->in_avail() == 0 );
}
</syntaxhighlight>
 
Using find:
/* OR */
<syntaxhighlight lang="cpp">
 
bool isNumeric( const char* pszInput, int nNumberBase )
{
Line 302 ⟶ 1,626:
return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
}
</syntaxhighlight>
</lang>
 
Using all_of (requires C++11)
=={{header|C sharp|C#}}==
<syntaxhighlight lang="cpp">
'''Framework:''' [[.NET]] 2.0+
bool isNumeric(const std::string& input) {
return std::all_of(input.begin(), input.end(), ::isdigit);
}
</syntaxhighlight>
 
=={{header|CFScript}}==
<lang csharp>public static bool IsNumeric(string s)
ColdFusion Script (CfScript)
{
<syntaxhighlight lang="cfm">isNumeric(42)</syntaxhighlight>
double Result;
return double.TryParse(s, out Result); // TryParse routines were added in Framework version 2.0.
}
 
string value = "123";
if (IsNumeric(value))
{
// do something
}</lang>
 
'''Framework:''' [[.NET]] 1.0+
 
<lang csharp>public static bool IsNumeric(string s)
{
try
{
Double.Parse(s);
return true;
}
catch
{
return false;
}
}</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lisplang="clojure">(defn numeric? [s]
(if-let [s (seq s)]
(let [s (if (= (first s) \-) (next s) s)
Line 341 ⟶ 1,646:
s (if (= (first s) \.) (next s) s)
s (drop-while #(Character/isDigit %) s)]
(empty? s))))</langsyntaxhighlight>
This works with any sequence of characters, not just Strings, e.g.:
<langsyntaxhighlight lisplang="clojure">(numeric? [\1 \2 \3]) ;; yields logical true</langsyntaxhighlight>
 
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:
<syntaxhighlight lang="clojure">
(require '[clojure.edn :as edn])
(import [java.io PushbackReader StringReader])
 
(defn number-string? [s]
(boolean
(when (and (string? s) (re-matches #"^[+-]?\d.*" s))
(let [reader (PushbackReader. (StringReader. s))
num (try (edn/read reader) (catch Exception _ nil))]
(when num
; Check that the string has nothing after the number
(= -1 (.read reader)))))))
</syntaxhighlight>
<syntaxhighlight lang="clojure">
user=> (number-string? "2r101010")
true
user=> (number-string? "22/7")
true
</syntaxhighlight>
 
=={{header|COBOL}}==
===Intrinsic Functions===
COBOL has the intrinsic functions <code>TEST-NUMVAL</code> and <code>TEST-NUMVAL-C</code> to check if a string is numeric (<code>TEST-NUMVAL-C</code> is used to check if it is also a monetary string). Implementations supporting the 20XX draft standard can also use <code>TEST-NUMVAL-F</code> for floating-point numbers. They return 0 if the string is valid, or the position of the first incorrect character.
 
<syntaxhighlight lang="cobol"> program-id. is-numeric.
procedure division.
display function test-numval-f("abc") end-display
display function test-numval-f("-123.01E+3") end-display
if function test-numval-f("+123.123") equal zero then
display "is numeric" end-display
else
display "failed numval-f test" end-display
end-if
goback.</syntaxhighlight>
 
===Implementation===
{{works with|OpenCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Is-Numeric.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Numeric-Chars PIC X(10) VALUE "0123456789".
01 Success CONSTANT 0.
01 Failure CONSTANT 128.
 
LOCAL-STORAGE SECTION.
01 I PIC 99.
 
01 Num-Decimal-Points PIC 99.
01 Num-Valid-Chars PIC 99.
 
LINKAGE SECTION.
01 Str PIC X(30).
 
PROCEDURE DIVISION USING Str.
IF Str = SPACES
MOVE Failure TO Return-Code
GOBACK
END-IF
 
MOVE FUNCTION TRIM(Str) TO Str
 
INSPECT Str TALLYING Num-Decimal-Points FOR ALL "."
IF Num-Decimal-Points > 1
MOVE Failure TO Return-Code
GOBACK
ELSE
ADD Num-Decimal-Points TO Num-Valid-Chars
END-IF
 
IF Str (1:1) = "-" OR "+"
ADD 1 TO Num-Valid-Chars
END-IF
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10
INSPECT Str TALLYING Num-Valid-Chars
FOR ALL Numeric-Chars (I:1) BEFORE SPACE
END-PERFORM
 
INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES
 
IF Num-Valid-Chars = FUNCTION LENGTH(Str)
MOVE Success TO Return-Code
ELSE
MOVE Failure TO Return-Code
END-IF
 
GOBACK
.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
The isFinite function is built into JavaScript, so we don't need to create our own function in CoffeeScript.
<langsyntaxhighlight lang="coffeescript">
console.log (isFinite(s) for s in [5, "5", "-5", "5", "5e5", 0]) # all true
console.log (isFinite(s) for s in [NaN, "fred", "###"]) # all false
</syntaxhighlight>
</lang>
 
 
=={{header|ColdFusion}}==
Adobe's ColdFusion
 
<langsyntaxhighlight lang="cfm"><cfset TestValue=34>
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
Line 372 ⟶ 1,767:
<cfelse>
is NOT Numeric.
</cfif></langsyntaxhighlight>
===Alternative solution===
 
<syntaxhighlight lang="text"><cfoutput>#isNumeric(42)#</cfoutput></syntaxhighlight>
 
=={{header|Common Lisp}}==
If the input may be relied upon to not be especially malicious, then it may be ''read'' and the result checked for being a number.
<langsyntaxhighlight lang="lisp">(defun numeric-string-p (string)
(let ((*read-eval* nil))
(ignore-errors (numberp (read-from-string string)))))</langsyntaxhighlight>
<code>ignore-errors</code> here handles returning nil in case the input is invalid rather than simply non-numeric.
 
However, <code>read</code>[<code>-from-string</code>] 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 <code>#*</code>, which takes a length). The [http://www.cliki.net/PARSE-NUMBER <code>parse-number</code>] library provides a numbers-only equivalent of <code>read</code>.
<langsyntaxhighlight lang="lisp">(defun numeric-string-p (string)
(handlerignore-case (prognerrors (parse-number:parse-number string))) ; parse failed, return false (nil)</syntaxhighlight>
t) ; parse succeeded, discard it and return true (t)
(parse-number::invalid-number ()
nil))) ; parse failed, return false (nil)</lang>
 
=={{header|D}}==
===Standard Version===
<lang d>import std.stdio, std.string, std.conv;
Using the standard Phobos function (currently binary and hex literals are not recognized):
 
<syntaxhighlight lang="d">import std.stdio, std.string, std.array;
 
void main() {
foreach (const s; ["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));
}</syntaxhighlight>
{{out}}
<pre>isNumeric("12"): true
isNumeric(" 12 "): true
isNumeric("hello12"): false
isNumeric("-12"): true
isNumeric("02"): true
isNumeric("0-12"): false
isNumeric("+12"): true
isNumeric("1.5"): true
isNumeric("1,000"): true
isNumeric("1_000"): true
isNumeric("0x10"): false
isNumeric("0b10101111_11110000_11110000_00110011"): false
isNumeric("-0b10101"): false
isNumeric("0x10.5"): false</pre>
 
===An Implementation===
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.array, std.exception;
 
bool isNumeric(in string s) pure {
immutable s2 = s.strip.toLower.replace("_", "").replace(",", "");
try {
s2.to!real;
} catch (ConvException e) {
if (s2.startsWith("0x"))
return !s2[2 .. $].to!ulong(16)
.collectException!ConvException;
else if (s2.startsWith("0b"))
return !s2[2 .. $].to!ulong(2)
.collectException!ConvException;
else
return false;
}
 
bool isNumeric(in string s) /*pure nothrow*/ {
try
to!real(s.strip());
catch (ConvException e)
return false;
return true;
}
 
void main() {
foreach (immutable s; ["12", " 12\t", "hello12", "-12", "02",
"0-12", "+12", "1.5"]), "1,000", "1_000",
"0x10", "0b10101111_11110000_11110000_00110011",
writefln(`isNumeric("%s") = %s`, s, isNumeric(s));
"-0b10101", "0x10.5"])
 
writefln(`isNumeric("%s"): %s`, s, s.isNumeric);
writeln("\nCurrently no hex or binary conversion:");
}</syntaxhighlight>
foreach (s; ["0x10", "6b"])
writefln(`isNumeric("%s") = %s`, s, isNumeric(s));
}</lang>
{{out}}
<pre>isNumeric("12") =: true
isNumeric(" 12 ") =: true
isNumeric("hello12") =: false
isNumeric("-12") =: true
isNumeric("02") =: true
isNumeric("0-12") =: false
isNumeric("+12") =: true
isNumeric("1.5") =: true
isNumeric("1,000"): true
 
isNumeric("1_000"): true
Currently no hex or binary conversion:
isNumeric("0x10"): = falsetrue
isNumeric("6b0b10101111_11110000_11110000_00110011"): = falsetrue
isNumeric("-0b10101"): false
</pre>
isNumeric("0x10.5"): false</pre>
 
=={{header|Delphi}}==
This simple function is a wrapper around a built-in Delphi function
 
<syntaxhighlight lang="delphi">
<lang Delphi>
function IsNumericString(const inStr: string): Boolean;
var
Line 434 ⟶ 1,865:
Result := TryStrToFloat(inStr,i);
end;
</syntaxhighlight>
</lang>
 
This console application tests the function:
 
<syntaxhighlight lang="delphi">
<lang Delphi>
program isNumeric;
 
Line 491 ⟶ 1,922:
end.
 
</syntaxhighlight>
</lang>
 
Example summarised output:
 
{{out}} Example summarised:
<pre>
123 is numeric
Line 503 ⟶ 1,933:
</pre>
 
=={{header|EDyalect}}==
<syntaxhighlight lang="dyalect">func String.IsNumeric() {
try {
parse(this) is Integer or Float
} catch _ {
false
}
}
var str = "1234567"
print(str.IsNumeric())</syntaxhighlight>
 
=={{header|Déjà Vu}}==
<lang e>def isNumeric(specimen :String) {
<syntaxhighlight lang="dejavu">is-numeric s:
true
try:
drop to-num s
catch value-error:
not
 
for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]:
!.( v is-numeric v )</syntaxhighlight>
{{out}}
<pre>"-3" true
"12ef" false
"12e3" true
"hello" false
"3.14" true
"0" true
"1" true</pre>
 
=={{header|E}}==
<syntaxhighlight lang="e">def isNumeric(specimen :String) {
try {
<import:java.lang.makeDouble>.valueOf(specimen)
Line 512 ⟶ 1,972:
return false
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
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"
.
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
The conversion function '''string->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
<syntaxhighlight lang="scheme">
(string->number "albert")
→ #f
(string->number -666)
→ -666
(if (string->number 666) 'YES 'NO)
→ YES
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule RC do
def is_numeric(str) do
case Float.parse(str) do
{_num, ""} -> true
_ -> false
end
end
end
 
["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1)</syntaxhighlight>
 
{{out}}
<pre>
["123", "-12.3", "-12e5", "+123"]
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
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
end
end
fun 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 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
value numeric
0o755 ⊤
thursday ⊥
3.14 ⊤
0b1010 ⊤
-100 ⊤
0xff ⊤
</pre>
 
=={{header|Erlang}}==
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 function <tt>is_number/1</tt>, 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 with <tt>is_number/1</tt>.
 
<langsyntaxhighlight lang="erlang">is_numeric(L) ->
Float = (catch erlang:list_to_float(L)),
Int = (catch erlang:list_to_integer(L)),
is_number(Float) orelse is_number(Int).</langsyntaxhighlight>
 
=={{header|EuphoriaERRE}}==
Short form using predeclared ERRE functions VAL and STR$.
<syntaxhighlight lang="erre">
PROGRAM NUMERIC
 
PROCEDURE IS_NUMERIC(S$->ANS%)
<lang Euphoria>include get.e
LOCAL T1,T1$
T1=VAL(S$)
T1$=STR$(T1)
ANS%=(T1$=S$) OR T1$=" "+S$
END PROCEDURE
 
BEGIN
PRINT(CHR$(12);)
INPUT("Enter a string",S$)
IS_NUMERIC(S$->ANS%)
IF ANS% THEN PRINT("is num") ELSE PRINT("not num")
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>Enter a string? 12.30
is num
</pre>
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">include get.e
 
function is_numeric(sequence s)
Line 530 ⟶ 2,098:
val = value(s)
return val[1]=GET_SUCCESS and atom(val[2])
end function</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let is_numeric a = fst (System.Double.TryParse( a))</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: numeric? ( string -- ? ) string>number >boolean ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
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.
 
<syntaxhighlight lang="java">
<lang fantom>
 
class Main
{
Line 567 ⟶ 2,135:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Output:
<pre>
For '2': true
Line 578 ⟶ 2,146:
</pre>
 
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.
 
<syntaxhighlight lang="java">
/* gary chike 08/27/2023 */
 
class Main {
static Void main() {
inputs := ["152\n", "-3.141", "Foo123", "-0", "456bar", "1.0E10"]
 
inputs.each |Str input| { echo("$input.trim \tis " + (isNumeric(input) ? "numeric" : "not numeric"))}
 
static Bool isNumeric(Str input) {
try {
input.toFloat
return true
}
catch(Err e) {
return false
}
}
}
</syntaxhighlight>
{{out}}
<pre>
152 is numeric
-3.141 is numeric
Foo123 is not numeric
-0 is numeric
456bar is not numeric
1.0E10 is numeric
</pre>
 
=={{header|Forth}}==
{{works with|gforth|0.6.2}}
<langsyntaxhighlight lang="forth">: is-numeric ( addr len -- )
2dup snumber? ?dup if \ not standard, but >number is more cumbersome to use
0< if
Line 602 ⟶ 2,201:
hex
s" beef" is-numeric \ beef as integer = BEEF
s" &1234" is-numeric \ &1234 as integer = 4D2 ( decimal literal )</langsyntaxhighlight>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">FUNCTION is_numeric(string)
 
<lang fortran>FUNCTION is_numeric(string)
IMPLICIT NONE
CHARACTER(len=*), INTENT(IN) :: string
Line 614 ⟶ 2,212:
READ(string,*,IOSTAT=e) x
is_numeric = e == 0
END FUNCTION is_numeric</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">function isNumeric(const potentialNumeric: string): boolean;
var
potentialInteger: integer;
potentialReal: real;
integerError: integer;
realError: integer;
begin
integerError := 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;
</syntaxhighlight>
 
The following is a more complete and compilable example.
 
<syntaxhighlight lang="pascal">
program IsNumeric;
 
type
TDynamicArrayItem = record
StrValue: string;
end;
 
var
myDynamicArray: array of TDynamicArrayItem;
i: Integer;
Value: Extended;
Code: Integer;
 
begin
// Initialize the dynamic array with different data types
SetLength(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 511
myDynamicArray[6].StrValue := '$A1'; // Hexadecimal representation for 161
 
// Iterate through the dynamic array and determine data type
for i := Low(myDynamicArray) to High(myDynamicArray) do
begin
Val(myDynamicArray[i].StrValue, Value, Code);
if Code = 0 then // The value 0 for Code indicates that the conversion was successful.
Writeln('Element ', i, ': Numeric Value ', Chr(9),' - ', Value) // Chr(9) = tab
else
Writeln('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. }
 
</syntaxhighlight>
 
{{out}}:
<pre>
Free Pascal Compiler version 3.2.2 [2021/10/28] for x86_64
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Darwin for x86_64
Compiling arrVariantIsNumeric.pas
Assembling arrvariantisnumeric
Linking arrVariantIsNumeric
37 lines compiled, 0.3 sec
 
Element 0: Non-Numeric Value - Hello
Element 1: Numeric Value - 4.20000000000000000000E+0001
Element 2: Numeric Value - 3.14158999999999999993E+0000
Element 3: Non-Numeric Value - World
Element 4: Numeric Value - 9.90000000000000000000E+0001
Element 5: Numeric Value - 7.77000000000000000000E+0002
Element 6: Non-Numeric Value - $A1
</pre>
 
=={{header|FreeBASIC}}==
FreeBASIC has a built-in Val() function which converts numeric strings to doubles. However, it is not ideal for the present task
since 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 on
this 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.
 
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim Shared symbols(0 To 15) As UByte
For i As Integer = 48 to 57
symbols(i - 48) = i
Next
For i As Integer = 97 to 102
symbols(i - 87) = i
Next
 
Const plus As UByte = 43
Const minus As Ubyte = 45
Const dot As UByte = 46
 
Function isNumeric(s As Const String, base_ As Integer = 10) As Boolean
If s = "" OrElse s = "." OrElse s = "+" OrElse s = "-" Then Return False
Err = 0
 
If base_ < 2 OrElse base_ > 16 Then
Err = 1000
Return False
End If
 
Dim t As String = LCase(s)
 
If (t[0] = plus) OrElse (t[0] = minus) Then
t = Mid(t, 2)
End If
 
If Left(t, 2) = "&h" Then
If base_ <> 16 Then Return False
t = Mid(t, 3)
End if
 
If Left(t, 2) = "&o" Then
If base_ <> 8 Then Return False
t = Mid(t, 3)
End if
 
If Left(t, 2) = "&b" Then
If base_ <> 2 Then Return False
t = Mid(t, 3)
End if
 
If Len(t) = 0 Then Return False
Dim As Boolean isValid, hasDot = false
For i As Integer = 0 To Len(t) - 1
isValid = False
 
For j As Integer = 0 To base_ - 1
If t[i] = symbols(j) Then
isValid = True
Exit For
End If
If t[i] = dot Then
If CInt(Not hasDot) AndAlso (base_ = 10) Then
hasDot = True
IsValid = True
Exit For
End If
Return False ' either more than one dot or not base 10
End If
Next j
 
If Not isValid Then Return False
Next i
 
Return True
End Function
 
Dim s As String
s = "1234.056789"
Print s, " (base 10) => "; isNumeric(s)
s = "1234.56"
Print s, " (base 7) => "; isNumeric(s, 7)
s = "021101"
Print s, " (base 2) => "; isNumeric(s, 2)
s = "Dog"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "Bad125"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "-0177"
Print s, " (base 8) => "; isNumeric(s, 8)
s = "+123abcd.ef"
Print s, " (base 16) => "; isNumeric(s, 8)
s = "54321"
Print s, " (base 6) => "; isNumeric(s, 6)
s = "123xyz"
Print s, " (base 10) => "; isNumeric(s)
s = "xyz"
Print s, " (base 10) => "; isNumeric(s)
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
1234.056789 (base 10) => true
1234.56 (base 7) => false
021101 (base 2) => false
Dog (base 16) => false
Bad125 (base 16) => true
-0177 (base 8) => true
+123abcd.ef (base 16) => false
54321 (base 6) => true
123xyz (base 10) => false
xyz (base 10) => false
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">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 if
end fn = flag
 
NSLog(@"%d",fn StringIsNumeric( @"1.23" ))
NSLog(@"%d",fn StringIsNumeric( @"-123.4e5" ))
NSLog(@"%d",fn StringIsNumeric( @"alpha" ))
 
HandleEvents</syntaxhighlight>
 
{{out}}
<pre>
1
1
0
</pre>
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim sAnswer, sString As String
 
sString = Trim(InputBox("Enter as string", "String or Numeric"))
 
If IsNumber(sString) Then sAnswer = "'" & sString & "' is numeric" Else sAnswer = "'" & sString & "' is a string"
Print sAnswer
 
End</syntaxhighlight>
Output:
<pre>
'Charlie' is a string
'-00.256666' is numeric
</pre>
 
=={{header|Go}}==
This uses a library function to meet the task's requirements:
<lang go>import "strconv"
<syntaxhighlight lang="go">package main
 
import (
func IsNumeric(s string) bool {
"fmt"
"strconv"
)
 
func isNumeric(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
}</lang>
 
func main() {
fmt.Println("Are these strings numeric?")
strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"}
for _, s := range strings {
fmt.Printf(" %4s -> %t\n", s, isNumeric(s))
}
}</syntaxhighlight>
 
{{out}}
<pre>
Are these strings numeric?
1 -> true
3.14 -> true
-100 -> true
1e2 -> true
NaN -> true
rose -> false
</pre>
 
This uses both a library function and a custom one but only checks for integerness:
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"strconv"
"unicode"
)
 
func isInt(s string) bool {
for _, c := range s {
if !unicode.IsDigit(c) {
return false
}
}
return true
}
 
func main() {
fmt.Println("Are these strings integers?")
v := "1"
b := false
if _, 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))
}</syntaxhighlight>
 
{{out}}
<pre>
Are these strings integers?
1 -> true
one -> false
</pre>
 
=={{header|Groovy}}==
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.
<langsyntaxhighlight lang="groovy">def isNumeric = {
def formatter = java.text.NumberFormat.instance
def pos = [0] as java.text.ParsePosition
Line 634 ⟶ 2,532:
// them the whole string was numeric
pos.index == it.size()
}</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">println isNumeric('1')
println isNumeric('-.555')
println isNumeric('1,000,000')
println isNumeric(' 1 1 1 1 ')
println isNumeric('abcdef')</langsyntaxhighlight>
 
{{out}}
Output:
<pre>true
true
Line 651 ⟶ 2,549:
 
=={{header|Haskell}}==
 
This function is not particularly useful in a statically typed language. Instead, one would just attempt to convert the string
to the desired type with ''read'' or ''reads'', and handle parsing failure appropriately.
Line 657 ⟶ 2,554:
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):
 
<langsyntaxhighlight lang="haskell">isInteger s = case reads s :: [(Integer, String)] of
[(_, "")] -> True
_ -> False
Line 666 ⟶ 2,563:
 
isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s</langsyntaxhighlight>
 
One can easily add ''isRational'', ''isComplex'' etc. following the same pattern.
Line 672 ⟶ 2,569:
Another way would be to use the Data.Char module, allowing code such as:
 
<langsyntaxhighlight lang="haskell">areDigits = all isDigit
isDigit selects ASCII digits i.e. '0'..'9'
isOctDigit selects '0'..'7'
isHexDigit selects '0'..'9','A'..'F','a'..'f'</langsyntaxhighlight>
 
so read s::Int (for instance) could be reliably used if string s passed these tests.
 
=={{header|Haxe}}==
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. <syntaxhighlight lang="actionscript">
static function isNumeric(n:String):Bool
{
if (Std.parseInt(n) != null) //Std.parseInt converts a string to an int
{
return true; //as long as it results in an integer, the function will return true
}
else
{
return false;
}
}
</syntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest"> ! = 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
Line 706 ⟶ 2,618:
isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L)
ENDIF
END</langsyntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">concept 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")
}</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
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.
<syntaxhighlight lang="icon">
<lang Icon>
write(image(x), if numeric(x) then " is numeric." else " is not numeric")
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">function isnumeric,input
on_ioerror, false
test = double(input)
return, 1
false: return, 0
end</langsyntaxhighlight>
 
Could be called like this:
 
<langsyntaxhighlight lang="idl">if isnumeric('-123.45e-2') then print, 'yes' else print, 'no'
; ==> yes
if isnumeric('picklejuice') then print, 'yes' else print, 'no'
; ==> no</langsyntaxhighlight>
 
=={{header|Insitux}}==
 
Non-null and non-false values are truthy in Insitux. The operation <b>to-num</b> returns null if it is unable to parse its string parameter, else the parsed number. The operation <b>bool</b> is unnecessary in most situations, but is composed with <b>to-num</b> here to satisfy the task specification.
 
<syntaxhighlight lang="insitux">> (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</syntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">isNumeric=: _ ~: _ ". ]
isNumericScalar=: 1 -: isNumeric
TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents'
sayIsNumericScalar=: , TXT {::~ isNumericScalar</langsyntaxhighlight>
Examples of use:
<langsyntaxhighlight lang="j"> isNumeric '152'
1
isNumeric '152 -3.1415926 Foo123'
Line 744 ⟶ 2,696:
0
sayIsNumericScalar '-3.1415926'
-3.1415926 represents a scalar numeric value.</langsyntaxhighlight>
 
=={{header|Java}}==
Typically, you would use the 'parse' methods from either the ''Integer'', ''Long'', ''Float'', or ''Double'' class, <br />which will throw a ''NumberFormatException'' for ill-formed values.<br />
For example
<syntaxhighlight lang="java">
Integer.parseInt("12345")
</syntaxhighlight>
<syntaxhighlight lang="java">
Float.parseFloat("123.456")
</syntaxhighlight>
The performance mark is somewhat negligible between a try-block and custom methods.
<syntaxhighlight lang="java">
public static void main(String[] args) {
String value;
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));
}
 
static boolean isInteger(String string) {
String digits = "0123456789";
for (char character : string.toCharArray()) {
if (!digits.contains(String.valueOf(character)))
return false;
}
return true;
}
 
static boolean isFloatingPoint(String string) {
/* at least one decimal-point */
int indexOf = string.indexOf('.');
if (indexOf == -1)
return false;
/* assure only 1 decimal-point */
if (indexOf != string.lastIndexOf('.'))
return false;
if (string.charAt(0) == '-' || string.charAt(0) == '+') {
string = string.substring(1);
indexOf--;
}
String integer = string.substring(0, indexOf);
if (!integer.isEmpty()) {
if (!isInteger(integer))
return false;
}
String decimal = string.substring(indexOf + 1);
if (!decimal.isEmpty())
return isInteger(decimal);
return true;
}
</syntaxhighlight>
<pre>
1234567 true
12345abc false
-123.456 true
-.456 true
123. true
123.abc false
</pre>
<br />
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.
<langsyntaxhighlight lang="java">public boolean isNumeric(String input) {
try {
Integer.parseInt(input);
Line 757 ⟶ 2,776:
return false;
}
}</langsyntaxhighlight>
 
Alternative 1 : Check that each character in the string is number. Note that this will only works for integers.
 
<langsyntaxhighlight lang="java">private static final boolean isNumeric(final String s) {
if (s == null || s.isEmpty()) return false;
for (int x = 0; x < s.length(); x++) {
Line 770 ⟶ 2,789:
}
return true; // valid
}</langsyntaxhighlight>
 
Alternative 2 : use a regular expression (a more elegant solution).
 
<langsyntaxhighlight lang="java">public static boolean isNumeric(String inputData) {
return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="java">public static boolean isNumeric(String inputData) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(inputData, pos);
return inputData.length() == pos.getIndex();
}</langsyntaxhighlight>
 
Alternative 4 : use the java.util.Scanner object. Very useful if you have to scan multiple entries.
 
<langsyntaxhighlight lang="java">public static boolean isNumeric(String inputData) {
Scanner sc = new Scanner(inputData);
return sc.hasNextInt();
}</langsyntaxhighlight>
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).
 
=={{header|JavaScript}}==
A far better validator can be found on StackOverflow[http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric]
<lang javascript>var value = "123.45e7"; // Assign string literal to value
<syntaxhighlight lang="javascript">function isNumeric(n) {
if (isFinite(value)) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var value = "123.45e7"; // Assign string literal to value
if (isNumeric(value)) {
// value is a number
}
//Or, in web browser in address field:
// javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isFiniteisNumeric(value)) {alert('numeric')} else {alert('non-numeric')}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
In versions of jq that support try/catch, the simplest way to test if a string can be parsed as a number is:<syntaxhighlight lang="jq">try tonumber catch false</syntaxhighlight>
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:
<syntaxhighlight lang="jq">def is_numeric: true and try tonumber catch false;</syntaxhighlight>
 
=={{header|Julia}}==
The function <tt>isnumber</tt> tests for strings that parse directly to numbers. This test excludes symbols, such as &pi; and <tt>1 + 1</tt>, 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.
 
<syntaxhighlight lang="julia">using Printf
 
isnumber(s::AbstractString) = tryparse(Float64, s) isa Number
 
tests = ["1", "-121", "one", "pi", "1 + 1", "NaN", "1234567890123456789", "1234567890123456789123456789",
"1234567890123456789123456789.0", "1.3", "1.4e10", "Inf", "1//2", "1.0 + 1.0im"]
 
for t in tests
fl = isnumber(t) ? "is" : "is not"
@printf("%35s %s a direct numeric literal.\n", t, fl)
end</syntaxhighlight>
 
{{out}}
<pre>
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.
 
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1
 
fun isNumeric(input: String): Boolean =
try {
input.toDouble()
true
} catch(e: NumberFormatException) {
false
}
 
fun main(args: Array<String>) {
val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
}</syntaxhighlight>
 
{{out}}
<pre>
152 is numeric
-3.1415926 is numeric
Foo123 is not numeric
-0 is numeric
456bar is not numeric
1.0E10 is numeric
</pre>
 
=={{header|LabVIEW}}==
{{VI solution|LabVIEW_Determine_if_a_string_is_numeric.png}}
 
=={{header|Lasso}}==
 
<lang Lasso>var('str'='12345');
{{works with|Lasso|8 & 9 }}
if( string_isNumeric($str) );
 
('Yes, it is numeric.');
<syntaxhighlight lang="lasso">local(str='12345')
/if;</lang>
string_isNumeric(#str) // true</syntaxhighlight>
 
{{works with|Lasso|9}}
 
<syntaxhighlight lang="lasso">'12345'->isdigit // true
'1X34Q'->isdigit // false</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
Line 870 ⟶ 2,965:
[NotNumber]
end function
</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<syntaxhighlight lang="lisaac">
<lang Lisaac>
"123457".is_integer.println;
// write TRUE on stdin
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">show number? "-1.23 ; true</langsyntaxhighlight>
 
=={{header|Lua}}==
This will also accept strings like "0xFF" or "314.16e-2" as numbers.
<langsyntaxhighlight lang="lua">if tonumber(a) ~= nil then
--it's a number
end;
</syntaxhighlight>
</lang>
 
=={{header|MathematicaM2000 Interpreter}}==
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.
<syntaxhighlight lang="m2000 interpreter">
\\ version 2
Module 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")
}
Checkit
 
</syntaxhighlight>
<lang Mathematica>NumberQ[ToExpression["02553352000242"]]</lang>
 
From 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.
 
<syntaxhighlight lang="m2000 interpreter">
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 parameter
 
Print isNumeric("+1"), isNumeric("-1"), isNumeric("1+")=false, isNumeric("1-")=false
Print 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")
 
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">isNumeric := proc(s)
try
if type(parse(s), numeric) then
printf("The string is numeric."):
else
printf("The string is not numeric."):
end if:
catch:
printf("The string is not numeric."):
end try:
end proc:</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">NumberQ[ToExpression["02553352000242"]]</syntaxhighlight>
 
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
function r = isnum(a)
r = ~isnan(str2double(a))
end
 
% tests
<lang MATLAB>
disp(isnum(123)) % 1
% Is string numeric?
disp(isnum("123")) % 1
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1
 
</syntaxhighlight>
function [out] = str_isnumeric(string)
 
=={{header|Maxima}}==
if ~ischar(string)
<syntaxhighlight lang="maxima">numberp(parse_string("170141183460469231731687303715884105727"));</syntaxhighlight>
error('str_isnumeric:NonCharacterArray','not a string input');
end
Nd = sum(isstrprop(string,'digit'));
Nc = length(string);
dN = Nc - Nd;
switch dN
case 0
out = 1;
otherwise
out = 0;
end
end
</lang>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn isNumeric str =
(
try
Line 927 ⟶ 3,102:
)
 
isNumeric "123"</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">(
dup (((int integer?) (pop false)) try) dip
((float float?) (pop false)) try or
) :numeric?</syntaxhighlight>
 
=={{header|MiniScript}}==
We rely on conversion to number returning a nonzero number, plus special checks for zero strings. Note that the <code>val</code> function is forgiving about additional characters ''after'' the number, so our function is too.
<syntaxhighlight lang="miniscript">isNumeric = function(s)
return s == "0" or s == "-0" or val(s) != 0
end function
 
print isNumeric("0")
print isNumeric("42")
print isNumeric("-3.14157")
print isNumeric("5@*#!")
print isNumeric("spam")</syntaxhighlight>
 
{{out}}
<pre>1
1
1
1
0</pre>
 
=={{header|MIPS Assembly}}==
<syntaxhighlight lang="mips">
# $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"
.text
main:
set_up: #test for 0th char == 45 or 46 or 48...57
la $a1,string
lb $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,1
lb $a0,($a1)
beqz $a0,exit_true # test for \0 null char
beq $a0,46,period_test #test for a duplicate period
blt $a0,48,exit_false #test for
bgt $a0,57,exit_false
la $a3,1 #set the HAS_DIGITS flag. This line is only reached because the
# tests for period and - both jump back to start.
j loop
exit_true:
beqz $a3,exit_false
la $a0,s_true
la $v0,4
syscall
 
li $v0,10
syscall
 
exit_false:
la $a0,s_false
la $v0,4
syscall
li $v0,10
syscall
period_test:
beq $a2,1,exit_false
li $a2,1
j loop
</syntaxhighlight>
 
=={{header|Mirah}}==
<langsyntaxhighlight lang="mirah">import java.text.NumberFormat
import java.text.ParsePosition
import java.util.Scanner
Line 1,054 ⟶ 3,310:
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')</langsyntaxhighlight>
 
=={{header|mIRC Scripting Language}}==
{{works with|mIRC}}
<langsyntaxhighlight lang="mirc">var %value = 3
if (%value isnum) {
echo -s %value is numeric.
}</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Numeric EXPORTS Main;
 
IMPORT IO, Fmt, Text;
Line 1,088 ⟶ 3,344:
IO.Put("isNumeric(-3.1415926) = " & Fmt.Bool(isNumeric("-3.1415926")) & "\n");
IO.Put("isNumeric(Foo123) = " & Fmt.Bool(isNumeric("Foo123")) & "\n");
END Numeric.</langsyntaxhighlight>
 
{{out}}
Output:
<pre>
isNumeric(152) = TRUE
Line 1,129 ⟶ 3,385:
USER>WRITE $SELECT($ISVALIDNUM("123e4"):"Valid",1:"Invalid"),!
Valid</pre>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def isNum(str)
try
double(str)
return true
catch
return false
end
end</syntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,149 ⟶ 3,415:
WriteLine($"$not is numeric: $(IsNumeric(not))");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
numeric digits 20
 
loop n_ over getTestData()
-- could have used n_.datatype('N') directly here...
if isNumeric(n_) then msg = 'numeric'
else msg = 'not numeric'
say ('"'n_'"').right(25)':' msg
end n_
 
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Pointless in NetRexx; the DATATYPE built-in-function is more powerful!
method isNumeric(testString) public static returns boolean
return testString.datatype('N')
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getTestData() private static returns Rexx[]
-- Coercing numbers into the Rexx type has the effect of converting them to strings.
-- NetRexx will still perform arithmetic on Rexx strings if those strings represent numbers.
-- Notice that whitespace between the sign and the number are ignored even when inside a string constant
testData = [ 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 -
]
return testData
</syntaxhighlight>
{{out}}
<pre>
" 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
</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import strutils
 
proc isNumeric(s: string): bool =
try:
discard s.parseFloat()
result = true
except ValueError:
result = false
 
const Strings = ["1", "3.14", "-100", "1e2", "Inf", "rose"]
 
for s in Strings:
echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric"</syntaxhighlight>
 
We could prefer to use the “parsutils” module which avoids the exception:
 
<syntaxhighlight lang="nim">import parseutils
 
proc isNumeric(s: string): bool =
var x: float
s.parseFloat(x) == s.len
 
const Strings = ["1", "3.14", "-100", "1e2", "Inf", "rose"]
 
for s in Strings:
echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric"</syntaxhighlight>
 
{{out}}
<pre>1 is numeric
3.14 is numeric
-100 is numeric
1e2 is numeric
Inf is numeric
rose is not numeric</pre>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
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)}}
</syntaxhighlight>
{{out}}
<pre>
╭───┬────────┬───────╮
│ # │ 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 │
╰───┴────────┴───────╯
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
class Numeric {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
IsNumeric(args[0])->PrintLine();
};
}
 
function : IsNumeric(str : String) ~ Bool {
return str->IsFloat();
}
}</syntaxhighlight>
 
=={{header|Objective-C}}==
Line 1,158 ⟶ 3,570:
The ''NSScanner'' class supports scanning of strings for various types. The ''scanFloat'' method will return YES if the string is numeric, even if the number is actually too long to be contained by the precision of a ''float''.
 
<langsyntaxhighlight lang="objc">if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] )
NSLog( @"\"-123.4e5\" is numeric" );
else
Line 1,167 ⟶ 3,579:
NSLog( @"\"Not a number\" is not numeric" );
// prints: "-123.4e5" is numeric
// prints: "Not a number" is not numeric</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="objc">BOOL isNumeric(NSString *s)
{
NSScanner *sc = [NSScanner scannerWithString: s];
Line 1,179 ⟶ 3,591:
}
return NO;
}</langsyntaxhighlight>
 
If we want to scan ''by 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, and
the '+' or '-' can appear only ''attached'' to the number ("+123" returns YES, but "+ 123" returns NO).
 
<langsyntaxhighlight lang="objc">BOOL isNumericI(NSString *s)
{
NSUInteger len = [s length];
Line 1,208 ⟶ 3,620:
}
return (i == len) && status;
}</langsyntaxhighlight>
 
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.
 
=={{header|OCaml}}==
 
This function is not particularly useful in a statically typed language. Instead, one would just attempt to convert the string
to the desired type and handle parsing failure appropriately.
Line 1,219 ⟶ 3,630:
The task doesn't define which strings are considered "numeric", so we do ints and floats, which should catch the most common cases:
 
<langsyntaxhighlight lang="ocaml">let is_int s =
try ignore (int_of_string s); true
with _ -> false
Line 1,227 ⟶ 3,638:
with _ -> false
 
let is_numeric s = is_int s || is_float s</langsyntaxhighlight>
 
=={{header|Octave}}==
 
The builtin function <tt>isnumeric</tt> return true (1) if the argument is a data of type ''number''; the provided function <tt>isnum</tt> 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.
 
<langsyntaxhighlight lang="octave">function r = isnum(a)
if ( isnumeric(a) )
r = 1;
else
or = str2num~isnan(str2double(a));
r = !isempty(o);
endif
endfunction
Line 1,247 ⟶ 3,656:
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1</langsyntaxhighlight>
 
=={{header|Odin}}==
STR2NUM uses internally the function eval(), therefore it should not be used for unsecured data (e.g. user input). Use instead str2double() or scanf().
 
<syntaxhighlight lang="odin">package main
<lang octave>function r = isnum(a)
 
if ( isnumeric(a) )
import "core:strconv"
r = 1;
import "core:fmt"
else
 
o = str2double(a);
is_numeric :: proc(s: string) -> bool {
r = !isnan(o);
_, ok := strconv.parse_f32(s)
endif
return ok
endfunction</lang>
}
 
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 numeric
3.14 is numeric
-100 is numeric
1e2 is numeric
Inf is not numeric
rose is not numeric
*/</syntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">fun {IsNumeric S}
{String.isInt S} orelse {String.isFloat S}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">isNumeric(s)={
my(t=type(eval(s)));
t == "t_INT" || t == "T_REAL"
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
See [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]].
<lang pascal>function IsNumeric(Value: string; const AllowFloat: Boolean): Boolean;
 
var
=={{header|PeopleCode}}==
ValueInt: Integer;
<syntaxhighlight lang="peoplecode">
ValueFloat: Extended;
Built-In Function
ErrCode: Integer;
Syntax
begin
 
// Check for integer: Val only accepts integers when passed integer param
Value := SysUtils.TrimIsNumber(Value);
Description
Val(Value, ValueInt, ErrCode);
 
Result := ErrCode = 0; // Val sets error code 0 if OK
Use the IsNumber function to determine if Value contains a valid numeric value. Numeric characters include sign indicators and comma and period decimal points.
if not Result and AllowFloat then
To determine if a value is a number and if it's in the user's local format, use the IsUserNumber function.
begin
 
// Check for float: Val accepts floats when passed float param
Parameters
Val(Value, ValueFloat, ErrCode);
 
Result := ErrCode = 0; // Val sets error code 0 if OK
Value
end;
Specify a string you want to search to determine if it is a valid number.
end;</lang>
 
Returns
A 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;
</syntaxhighlight>
 
=={{header|Perl}}==
{{works with|Perl|5.8}}
<langsyntaxhighlight lang="perl">use Scalar::Util qw(looks_like_number);
print looks_like_number($str) ? "numeric" : "not numeric\n";</langsyntaxhighlight>
 
{{works with|Perl|5.8}}
Line 1,302 ⟶ 3,741:
Assuming that you don't care about [[IEEE]] notations like "NaN" or "Infinity", you probably just want to use a [[Regular expression matching|regular expression]].
 
<langsyntaxhighlight lang="perl">if (/\D/) { print "has nondigits\n" }
if (/^\d+\z/) { print "is a whole number\n" }
if (/^-?\d+\z/) { print "is an integer\n" }
Line 1,309 ⟶ 3,748:
if (/^-?(?:\d+(?:\.\d*)?&\.\d+)\z/) { print "is a decimal number\n" }
if (/^([+-]?)(?=\d&\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\z/)
{ print "a C float\n" }</langsyntaxhighlight>
 
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.
Line 1,315 ⟶ 3,754:
If you're on a [[POSIX]] 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?''
 
<langsyntaxhighlight lang="perl">sub getnum {
use POSIX;
my $str = shift;
Line 1,329 ⟶ 3,768:
}
 
sub is_numeric { defined getnum($_[0]) }</langsyntaxhighlight>
 
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.
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>sub is-number( $term --> Bool ) {
<span style="color: #008080;">function</span> <span style="color: #000000;">isNumber</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
$term ~~ /\d/ and +$term ~~ Numeric;
<span style="color: #008080;">return</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%f"</span><span style="color: #0000FF;">)!={}</span>
}
<span style="color: #000080;font-style:italic;">-- Alt: isNumberString(object s) and
say "true" if is-number( 10111 );</lang>
-- return string(s) and scanf(s,"%f")!={}, or even
-- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"#a"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0xA"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0(16)A"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#FF"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"255"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"0."</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0.0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"000.000"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0e0"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0e-2000"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">".14"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">".05"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-5.2"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0xf"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ten"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1B"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#1B"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">" 12 "</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" 12 "</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0o16"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0o18"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"0b10101111_11110000_11110000_00110011"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"1_000"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"50e"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"+123"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"+ 123"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-0b10101"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"NaN"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"+.345"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"12..34"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"12e3.4"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0-2"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"192.168.0.1"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1.2e"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1 2"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"12.34"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"beef"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#beef"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1,000,000"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Inf"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1/2"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"1.5e+27"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0x10.5"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1."</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">numeric</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span>
<span style="color: #000000;">notnumb</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">isNumber</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">numeric</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numeric</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">notnumb</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">notnumb</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numeric: "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numeric</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Indent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nnot numeric: "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">notnumb</span><span style="color: #0000FF;">,{</span><span style="color: #004600;">pp_Indent</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
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.`}
</pre>
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.
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$string = '123';
if(is_numeric(trim($string) && !ctype_space($string[0])) {
}
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
The '[http://software-lab.de/doc/refF.html#format format]' function can
be used for that. It returns NIL if the given string is not a legal number
<langsyntaxhighlight PicoLisplang="picolisp">: (format "123")
-> 123
 
Line 1,356 ⟶ 3,837:
 
: (format "-123.45" 4)
-> 1234500</langsyntaxhighlight>
 
=={{header|Pike}}==
 
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.
 
<syntaxhighlight lang="pike">
<lang Pike>
int(0..1) is_number(string s)
{
Line 1,376 ⟶ 3,856:
is_number(num);
-> true
</syntaxhighlight>
</lang>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
is_numeric: procedure (text) returns (bit (1));
declare text character (*);
Line 1,391 ⟶ 3,871:
done:
return ('0'b);
end is_numeric;</langsyntaxhighlight>
<pre>
5 '1'B
Line 1,401 ⟶ 3,881:
 
=={{header|PL/SQL}}==
<langsyntaxhighlight lang="plsql">FUNCTION IsNumeric( value IN VARCHAR2 )
RETURN BOOLEAN
IS
Line 1,411 ⟶ 3,891:
WHEN others THEN
return( FALSE );
END;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="plsql">Value VARCHAR2( 10 ) := '123';
IF( IsNumeric( Value ) )
THEN
NULL;
END IF;</langsyntaxhighlight>
 
=={{header|Plain English}}==
The following decider exists in the noodle
<code>To decide if a string is any numeric literal:</code>
<br />
and is used to resolve the If clause
<code>If the string is any numeric literal,</code>
in this solution.
<syntaxhighlight lang="plainenglish">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.</syntaxhighlight>
{{out}}
<pre>
cat -> no
3 -> yes
+3 -> yes
-123 -> yes
123,456 -> no
11/5 -> yes
-26-1/3 -> yes
+26-1/3 -> yes
1/0 -> yes
3.14159 -> no
</pre>
 
=={{header|PowerShell}}==
Note: PowerShell 1.0 does not support 'try'
THis simply tries arithmetic with the argument and if that fails, ''false'' is returned.
<langsyntaxhighlight lang="powershell">function isNumeric ($x) {
try {
0 + $x | Out-Null
Line 1,429 ⟶ 3,949:
return $false
}
}</langsyntaxhighlight>
 
But this one doesn't work for strings like "8." though a . is appended it returns true!
Line 1,435 ⟶ 3,955:
Alternatively, you can use the static System.Int32.TryParse() method in the .NET framework.
 
<langsyntaxhighlight lang="powershell">function isNumeric ($x) {
$x2 = 0
$isNum = [System.Int32]::TryParse($x, [ref]$x2)
return $isNum
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|7}}
 
The code:
 
<syntaxhighlight lang="prolog">numeric_string(String) :-
atom_string(Atom, String),
atom_number(Atom, _).</syntaxhighlight>
 
A predicate to test the code:
 
<syntaxhighlight lang="prolog">test_strings(Strings) :-
forall( member(String, Strings),
( ( numeric_string(String)
-> Result = a
; Result = 'not a' ),
format('~w is ~w number.~n', [String, Result])
)
).</syntaxhighlight>
 
Example of using the test predicate:
 
<syntaxhighlight lang="prolog">?- 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.</syntaxhighlight>
 
=={{header|PureBasic}}==
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.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure IsNumeric(InString.s, DecimalCharacter.c = '.')
#NotNumeric = #False
#IsNumeric = #True
Line 1,496 ⟶ 4,046:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
Sample output:
<pre>'+3183.31151E+321' = 1
'-123456789' = 1
Line 1,504 ⟶ 4,054:
 
=={{header|Python}}==
===Python: Simple int/float===
<lang python>s = '123'
<syntaxhighlight lang="python">def is_numeric(s):
try:
i = float(s)try:
float(s)
except ValueError, TypeError:
# not numeric return True
except (ValueError, TypeError):
else:
# numeric</lang> return False
 
is_numeric('123.0')</syntaxhighlight>
 
Or for positive integers only:
 
<syntaxhighlight lang ="python">s = '123'.isdigit()</syntaxhighlight>
if s.isdigit():
# numeric</lang>
 
===Python: Most numeric literals===
Including complex, hex, binary, and octal numeric literals we get:
<langsyntaxhighlight lang="python">def is_numeric(litliteral):
'"""Return valuewhether of numerica literal stringcan orbe ValueErrorparsed exception'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</syntaxhighlight>
 
Sample use, including value parsed, its type, and standard method str.isnumeric():
# Handle '0'
<syntaxhighlight lang="python">def numeric(literal):
if lit == '0': return 0
"""Return value of numeric literal or None if can't parse a value"""
# Hex/Binary
castings = [int, float, complex,
litneg = lit[1:] if lit[0] == '-' else lit
lambda s: int(s,2), #binary
if litneg[0] == '0':
iflambda litneg[1]s: inint(s,8), 'xX': #octal
lambda returns: int(lits,16)] #hex
for elif litneg[1]cast in 'bB'castings:
return int(lit,2)try:
else: return cast(literal)
except tryValueError:
return int(lit,8)pass
return None
except ValueError:
pass
 
# Int/Float/Complex
try:
return int(lit)
except ValueError:
pass
try:
return float(lit)
except ValueError:
pass
return complex(lit)</lang>
Sample use:
<lang python>>>> for s in ['0', '00', '123', '-123.', '-123e-4', '0123', '0x1a1', '-123+4.5j', '0b0101', '0.123', '-0xabc', '-0b101']:
print "%14s -> %-14s %s" % ('"'+s+'"', is_numeric(s), type(is_numeric(s)))
 
tests = [
"0" -> 0 <type 'int'>
'0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04',
"00" -> 0 <type 'int'>
"'0.123"', ->'(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', <type'-0xABC', 'int0x1a1'>,
'12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02',
"-123." -> -123.0 <type 'float'>
'NaN', 'inf', '-Infinity']
"-123e-4" -> -0.0123 <type 'float'>
 
"0123" -> 83 <type 'int'>
for s in tests:
"0x1a1" -> 417 <type 'int'>
print("%14s -> %-14s %-20s is_numeric: %-5s str.isnumeric: %s" % (
"-123+4.5j" -> (-123+4.5j) <type 'complex'>
'"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))</syntaxhighlight>
"0b0101" -> 5 <type 'int'>
{{out}}
"0.123" -> 0.123 <type 'float'>
<pre>
"-0xabc" -> -2748 <type 'int'>
"-0b1010" -> -50 <typeclass 'int'> is_numeric: True str.isnumeric: True
"0." -> 0.0 <class 'float'> is_numeric: True str.isnumeric: False
>>></lang>
"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</pre>
 
===Python: Regular expressions===
<syntaxhighlight lang="python">import re
numeric = re.compile('[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?')
is_numeric = lambda x: numeric.fullmatch(x) != None
 
is_numeric('123.0')</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 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</syntaxhighlight>
 
{{out}}
 
<pre>152 is a valid number.
-3.1415926 is a valid number.
Foo123 is not a valid number.</pre>
 
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">> strings <- c("152", "-3.1415926", "Foo123")
> suppressWarnings(!is.na(as.numeric(strings)))
[1] TRUE TRUE FALSE
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">(define (string-numeric? s) (number? (string->number s)))</syntaxhighlight>
Or, since all non-<tt>#f</tt> are true:
<syntaxhighlight lang="racket">(define string-numeric? string->number)</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.11}}
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.
 
<syntaxhighlight lang="raku" line>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;</syntaxhighlight>
 
<pre> 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</pre>
 
=={{header|RapidQ}}==
<syntaxhighlight lang RapidQ="rapidq">isnumeric </lang>
$Typecheck on
 
Line 1,622 ⟶ 4,287:
showmessage (str$(isNumeric("-152.34","")))
end
</syntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
<lang REBOL>
REBOL [
Title: "Is Numeric?"
Author: oofoe
Date: 2009-12-04
URL: http://rosettacode.org/wiki/IsNumeric
]
Line 1,660 ⟶ 4,324:
} none
foreach x cases [print [x numeric? x pnumeric? x]]
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
Retro does not have floating point numbers as part of the core system. For others, itthis can be providesdone '''isNumber?'''with:
 
<syntaxhighlight lang="retro">'123 a:from-string TRUE [ swap c:digit? and ] a:reduce</syntaxhighlight>
<lang Retro>"123" isNumber?</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program to determinedetermines 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= 2
zzz= '000000000004'
zzz= '+5'
zzz=' +6 '+5
zzz= ' + 76 '
zzz= ' -+ 87 '
zzz= ' - .98 '
zzz= ' - 19.9'
zzz= '- 19.7'
zzz= '2e3.7'
zzz=47e567 .7
zzz= '2e-32e3'
zzz='1.2e1' 47e567
zzz=' .2E6'2e-3'
zzz= ' 21.e5 2e1'
zzz= ' +1.2E0002 2E6'
zzz= ' +12.2e+002e5 '
zzz= ' +00000011.200e+0022E0002 '
zzz= ' - 000001 +1.200e2e+002 '
zzz=' -' 000008+0000001.201e-00000000000000002200e+002 '
zzz= ' - 000001.200e+002 '
zzz= ' - 000008.201e-00000000000000002 '
 
/*Note: some REXX interpretorsinterpreters allow use of tab chars as blanks. */
 
/*all statements below are equivalent.*/
 
if \datatype(yyy, 'n') then say 'oops, not numeric:' yyy
if \datatype(yyy, 'N') then say 'oops, not numeric:' yyy
if ¬datatype(yyy, 'N') then say 'oops, not numeric:' yyy
if ¬datatype(yyy, 'numeric') then say 'oops, not numeric:' yyy
if ¬datatype(yyy, 'nimrod.') then say 'oops, not numeric:' yyy
if datatype(yyy) \== 'NUM' then say 'oops, not numeric:' yyy
if datatype(yyy) /== 'NUM' then say 'oops, not numeric:' yyy
if datatype(yyy) ¬== 'NUM' then say 'oops, not numeric:' yyy
if datatype(yyy) ¬= 'NUM' then say 'oops, not numeric:' yyy
 
/*note: REXX only looks at the first char for DATATYPE's 2nd argargument. */
 
/*note: some REXX interpretorsinterpreters don't support the ¬ (not) character. */</langsyntaxhighlight>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
see isdigit("0123456789") + nl + # print 1
isdigit("0123a") # print 0
</syntaxhighlight>
 
=={{header|RPL}}==
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 0 '''ELSE''' TYPE { 0 1 10 } SWAP POS SIGN '''END''' ≫ ‘<span style="color:blue">NUM?</span>’ STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def is_numeric?(s)
begin
Float(s)
Line 1,724 ⟶ 4,400:
true # numeric
end
end</langsyntaxhighlight>
 
or more compact:
 
<langsyntaxhighlight lang="ruby">def is_numeric?(s)
!!Float(s) rescue false
end</langsyntaxhighlight>
 
'''NB!''' Since Ruby 2.6 you no longer need `rescue`:
 
<syntaxhighlight lang="ruby">def is_numeric?(s)
!!Float(s, exception: false)
end</syntaxhighlight>
 
Adding `exception: false` will make it return `nil` instead.
 
'''sample'''
<syntaxhighlight lang="ruby">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</syntaxhighlight>
{{out}}
<pre>
"0" => true
"0.0" => true
"-123" => true
"abc" => false
"0x10" => true
"0xABC" => true
"123a" => false
"-123e3" => true
"0.1E-5" => true
"50e" => false
</pre>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">print isNumeric("123")
print isNumeric("1ab")
 
' ------------------------
' Numeric Check
' 0 = bad
' 1 = good
' ------------------------
FUNCTION isNumeric(f$)
isNumeric = 1
f$ = 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 = 0
dot$ = "."
goto [nxtDigit]
end if
if (d$ < "0") or (d$ > "9") then isNumeric = 0
[nxtDigit]
next i
END FUNCTION</syntaxhighlight><pre>123 1
1ab 0</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">// 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()
}</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
import scala.util.control.Exception.allCatch
 
def isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
</syntaxhighlight>
 
<syntaxhighlight lang="scala">
def isNumeric(input: String): Boolean = input.forall(_.isDigit)
</syntaxhighlight>
</lang>
 
Or a more complete version, using a complex regular expression:
<syntaxhighlight lang="scala">
def isNumeric2(str: String): Boolean = {
str.matches(s"""[+-]?((\d+(e\d+)?[lL]?)|(((\d+(\.\d*)?)|(\.\d+))(e\d+)?[fF]?))""")
}
</syntaxhighlight>
 
Or using the built-in number parsing and catching exceptions:
<syntaxhighlight lang="scala">
def isNumeric(str: String): Boolean = {
!throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble)
}
def throwsNumberFormatException(f: => Any): Boolean = {
try { f; false } catch { case e: NumberFormatException => true }
}
</syntaxhighlight>
 
=={{header|Scheme}}==
string->number returns #f when the string is not numeric and otherwise the number, which is non-#f and therefore true.
<langsyntaxhighlight lang="scheme">(define (numeric? s) (string->number s))</langsyntaxhighlight>
 
=={{header|Seed7}}==
The function isNumeric uses the function [http://seed7.sourceforge.net/libraries/scanstri.htm#getNumber%28inout_string%29 getNumber] from the library [http://seed7.sourceforge.net/libraries/scanstri.htm scanstri.s7i].
GetNumber reads a numeric literal from a string. The numeric literal is removed from the input string.
 
<syntaxhighlight lang="seed7">$ 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;</syntaxhighlight>
 
=={{header|Sidef}}==
There is the the ''String.looks_like_number'' method, which returns true when a given strings looks like a number:
<syntaxhighlight lang="ruby">say "0.1E-5".looks_like_number; #=> true</syntaxhighlight>
 
Alternatively, we can use regular expressions to determine this:
 
<syntaxhighlight lang="ruby">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/)
}</syntaxhighlight>
 
Sample:
<syntaxhighlight lang="ruby">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)))
}</syntaxhighlight>
{{out}}
<pre>
0 => true
0.0 => true
-123 => true
abc => false
0x10 => true
0xABC => true
123a => false
-123e3 => true
0.1E-5 => true
50e => false
</pre>
 
=={{header|Simula}}==
Simula uses the '&' instead of 'e' or 'E' for the exponent part of a floating point decimal number.
 
<syntaxhighlight lang="simula">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;
 
END
</syntaxhighlight>
{{out}}
<pre>
0.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&+022
 
NOT NUMERIC ""
NOT NUMERIC "5."
NOT NUMERIC "5&"
NOT NUMERIC "5&+"
NOT NUMERIC "5.&"
NOT NUMERIC "5.&-"
NOT NUMERIC "5.&10"
</pre>
 
=={{header|Smalltalk}}==
Line 1,745 ⟶ 4,654:
The String class has the method <code>isNumeric</code>; this method (at least on version 3.0.4) does not recognize as number strings like '-123'! So I've written an extension...
 
<langsyntaxhighlight lang="smalltalk">String extend [
realIsNumeric [
(self first = $+) |
Line 1,764 ⟶ 4,673:
'-3.78.23'. "false"
'123e3' "false: the notation is not recognized"
} do: [ :a | a realIsNumeric printNl ]</langsyntaxhighlight>
 
{{works with|Smalltalk/X}}
=={{header|SNOBOL4}}==
{{works with|GNU Smalltalk}}
(should work with all)
<syntaxhighlight lang="smalltalk">(Number readFrom:(aString readStream) onError:[nil]) notNil</syntaxhighlight>
to handle radix numbers (such as 2r10111), use:
<syntaxhighlight lang="smalltalk">(Scanner scanNumberFrom:(aString readStream)) notNil</syntaxhighlight>
 
=={{header|SNOBOL4}}==
This task is easy in Snobol. Use the convert( ) function as a predicate returning success (T) or failure (F) for string to real conversion.
 
<langsyntaxhighlight Snobol4lang="snobol4"> define('nchk(str)') :(nchk_end)
nchk convert(str,'real') :s(return)f(freturn)
nchk_end
Line 1,789 ⟶ 4,704:
output = isnum('abc')
output = isnum('A440')
end</langsyntaxhighlight>
 
{{out}}
Output:
<pre>T: 123
T: 123.0
Line 1,803 ⟶ 4,718:
=={{header|SQL}}==
{{works with|MS SQL|Server 2005}}
<langsyntaxhighlight lang="sql">declare @s varchar(10)
set @s = '1234.56'
 
Line 1,809 ⟶ 4,724:
 
if isnumeric(@s)=1 begin print 'Numeric' end
else print 'Non-numeric'</langsyntaxhighlight>
 
=={{header|StandardSQL MLPL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
CREATE OR REPLACE FUNCTION IS_NUMERIC (
<lang sml>(* this function only recognizes integers in decimal format *)
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(' ')@
</syntaxhighlight>
Output:
<pre>
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.
</pre>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">(* 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
Line 1,822 ⟶ 4,849:
| NONE => false
 
fun isNumeric s = isInteger s orelse isReal s</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<syntaxhighlight lang="swift">func isNumeric(a: String) -> Bool {
return Double(a) != nil
}</syntaxhighlight>
 
{{works with|Swift|1.x}}
This one only checks whether it is an integer:
<syntaxhighlight lang="swift">func isNumeric(a: String) -> Bool {
return a.toInt() != nil
}</syntaxhighlight>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc isNumeric str {string is double -strict $str}</syntaxhighlight>
<lang tcl>if {
[string is double -strict $varname]
} then { ... }</lang>
 
=={{header|TMG}}==
Also <tt>string is integer</tt> (, <tt>string is alnum</tt> etc etc)
Unix TMG dialect. NOTE: the program also performs some basic normalization (namely, removing the plus sign and translating "E" to "e"):
<syntaxhighlight lang="unixtmg">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: !<<
>>;</syntaxhighlight>
 
Sample input:
<pre>
123
+12345.678
.678
1.
+1.0E+99
-7.
-123e-123
00000
.
1.2.3
0x123
a1-a5
1 000 000
1,000,000
1.00e1e1
</pre>
 
Sample output:
<pre> True: 123
True: 12345.678
True: .678
True: 1.
True: 1.0e99
True: -7.
True: -123e-123
True: 00000
False: .
False: 1.2.3
False: 0x123
False: a1-a5
False: 1 000 000
False: 1,000,000
False: 1.00e1e1
</pre>
 
=={{header|Toka}}==
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.
 
<langsyntaxhighlight lang="toka">[ ( string -- flag )
>number nip ] is isNumeric
 
Line 1,843 ⟶ 4,938:
" 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 )</langsyntaxhighlight>
 
 
=={{header|True BASIC}}==
{{trans|RapidQ}}
<syntaxhighlight lang="basic">
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 FUNCTION
END
</syntaxhighlight>
 
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="bash">
#!/bin/bash
isnum() {
printf "%f" $1 >/dev/null 2>&1
}
 
 
check() {
if isnum $1
then
echo "$1 is numeric"
else
echo "$1 is NOT numeric"
fi
}
 
check 2
check -3
check +45.44
check -33.332
check 33.aa
check 3.3.3
</syntaxhighlight>
 
{{out}}
<pre>
2 is numeric
-3 is numeric
+45.44 is numeric
-33.332 is numeric
33.aa is NOT numeric
3.3.3 is NOT numeric
</pre>
 
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">def isnum (string str)
try
double str
return true
catch valueerror
return false
end try
end isnum</syntaxhighlight>
 
=={{header|VBA}}==
In France, IsNumeric("123.45") return False.
So we have to check the "." or "," and replace it by the Application.DecimalSeparator.
 
<syntaxhighlight lang="vb">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 Sub
 
Private Function Is_Numeric(s As String) As Boolean
Dim Separat As String, Other As String
Separat = Application.DecimalSeparator
Other = IIf(Separat = ",", ".", ",")
Is_Numeric = IsNumeric(Replace(s, Other, Separat))
End Function</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang ="vb">IsNumeric(Expr)</langsyntaxhighlight>
 
Returns a True if numeric and a false if not.
Line 1,854 ⟶ 5,084:
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.
<langsyntaxhighlight lang="vedit">:IS_NUMERIC:
if (Num_Eval(SUPPRESS)==0 && Cur_Char != '0') {
Return(FALSE)
} else {
Return(TRUE)
}</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2005}}
<langsyntaxhighlight lang="vbnet">Dim Value As String = "+123"
 
If IsNumeric(Value) Then
PRINT "It is numeric."
End If</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import strconv
 
fn 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)}")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Are these strings numeric?
1 -> true
3.14 -> true
-100 -> true
1e2 -> true
NaN -> false
rose -> false
0xff -> true
0b110 -> true
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
Wren's Num class already has a static method which does what this task requires.
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
System.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")")
}</syntaxhighlight>
 
{{out}}
<pre>
Are these strings numeric?
1 -> yes
3.14 -> yes
-100 -> yes
1e2 -> yes
NaN -> yes
0xaf -> yes
rose -> no
</pre>
 
=={{header|XLISP}}==
The inbuilt function <tt>STRING->NUMBER</tt> returns the numeric value of a string if it can. We discard this value and return the Boolean value 'true'; otherwise, the <tt>IF</tt> conditional will not be satisfied and will return 'false'.
<syntaxhighlight lang="xlisp">(DEFUN NUMERICP (X)
(IF (STRING->NUMBER X) T))</syntaxhighlight>
 
=={{header|XPL0}}==
The compiler is more strict in the characters it accepts as numeric than
what is accepted here. This program indicates more of what the input
intrinsics (IntIn, RlIn and HexIn) would accept as numeric.
<syntaxhighlight lang "XPL0">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);
];
]</syntaxhighlight>
{{out}}
<pre>
Are these strings numeric?
yes : 1
yes : 3.14
yes : -100
yes : 1e2
no : NaN
yes : $af
yes : %1_1011
no : rose
yes : . 3
yes : num9
yes : x$ 9
no : x$ a
</pre>
 
=={{header|Z80 Assembly}}==
{{works with|CP/M 3.1|YAZE-AG-2.51.2 Z80 emulator}}
{{works with|ZSM4 macro assembler|YAZE-AG-2.51.2 Z80 emulator}}
Use the /S8 switch on the ZSM4 assembler for 8 significant characters for labels and names
<syntaxhighlight lang="z80">
;
; 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
;
 
bdos equ 05h ; Call to CP/M BDOS function
strdel equ 6eh ; Set string delimiter
readstr equ 0ah ; Read string from console
wrtstr equ 09h ; Write string to console
 
nul equ 00h ; ASCII control characters
esc equ 1bh
cr equ 0dh
lf equ 0ah
 
cnull equ '0' ; ASCII character constants
cnine equ '9'
cminus equ '-'
cdot equ '.'
 
buflen equ 30h ; Length of input buffer
minbit equ 00h ; Bit 0 is used as flag for '-'
dotbit equ 01h ; Bit 1 is used as flag for '.'
 
;
; Macros for BDOS calls
;
 
setdel macro char ; Set string delimiter to char
ld c,strdel
ld e,char
call bdos
endm
 
print macro msg ; Output string to console
ld c,wrtstr
ld de,msg
call bdos
endm
 
newline macro ; Print newline
ld c,wrtstr
ld de,crlf
call bdos
endm
 
readln macro buf ; Read a line from input
ld c,readstr
ld de,buf
call bdos
endm
 
;
; =====================
; Start of main program
; =====================
;
 
cseg
 
isnum:
setdel nul ; Set string terminator to nul ('\0') - '$' is default in CP/M
print help
newline
newline
 
readnum:
ld b,buflen ; Clear input buffer
ld hl,bufcont
clrloop:
ld (hl),0
inc hl
djnz clrloop
 
readln inputbuf ; Read a line from input
newline ; Newline is discarded during input, so write one...
 
ld a,(inputbuf+1) ; Length of actual input
cp 0 ; If empty input, quit
ret z
 
ld b,a ; Loop counter for djnz instruction
ld c,0 ; Use c for flags: '-' and '.' may be encountered at most once, '-' only at start
ld hl,bufcont ; Start of actual input
 
loop:
ld a,(hl) ; Get next character into a
 
cp cminus ; Check minus sign
jr z,chkminus
 
cp cdot ; Check dot
jr z,chkdot
 
cp cnull ; Check if below '0'
jr c,notanum
 
cp cnine+1 ; Check if above '9'
jr nc,notanum
 
checknxt:
set minbit,c ; Whatever the case, no more '-' are allowed after the first character
inc hl ; Increase hl to next character and repeat until done
djnz loop
 
print bufcont ; If we made it this far, we are done and the string is numeric
print yesmsg
newline
newline
 
done:
jp readnum ; Read next input from user until terminated with ^C or empty input
ret ; Return to CP/M (unreachable code)
 
notanum:
print bufcont ; Print failure message
print nomsg
newline
newline
jr done
 
chkminus:
bit minbit,c ; If a '-' is encountered and the flag is already set, the string is not numeric
jr nz,notanum
set minbit,c ; Otherwise, set flag and check next character
jr checknxt
 
chkdot:
bit dotbit,c ; If a '.' is encountered and the flag is already set, the string is not numeric
jr nz,notanum
set dotbit,c ; Otherwise, set flag and check next character
jr checknxt
 
;
; ===================
; End of main program
; ===================
;
 
;
; ================
; Data definitions
; ================
;
 
dseg
 
help:
defz 'Enter numbers to check, end with empty line or ^C'
 
inputbuf: ; Input buffer for CP/M BDOS call
defb buflen ; Maximum possible length
defb 00h ; Returned length of actual input
bufcont:
defs buflen ; Actual input area
defb nul ; Null terminator for output, if buffer is filled completely
 
yesmsg:
defz ' is numeric'
nomsg:
defz ' is not numeric'
 
crlf: defb cr,lf,nul ; Generic newline
 
</syntaxhighlight>
 
{{out}}
<pre>
E>isnum
Enter numbers to check, end with empty line or ^C
 
1234
1234 is numeric
 
hello
hello is not numeric
 
12.34
12.34 is numeric
 
-98.76
-98.76 is numeric
 
4.6.76
4.6.76 is not numeric
 
34-56-23
34-56-23 is not numeric
 
-.9876543210
-.9876543210 is numeric
 
444555.
444555. is numeric
 
1234c
1234c is not numeric
 
123e45
123e45 is not numeric
 
</pre>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn isNum(text){
try{ text.toInt(); True }
catch{ try{ text.toFloat(); True }
catch{ False }
}
}</syntaxhighlight>
<pre>
isNum("123.4") //-->True
isNum("123") //-->True
isNum("-123.4") //-->True
isNum("123.4x") //-->False
isNum("hoho") //-->False
isNum(123.4) //-->True
isNum(123) //-->True
</pre>
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: 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
</syntaxhighlight>
 
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Numeric.png Determine if string is numeric]
 
{{omit from|GUISS}}
3

edits