Determine if a string is numeric: Difference between revisions

Rename Perl 6 -> Raku, alphabetize, minor clean-up
m (→‎{{header|Phix}}: merge <lang> tags)
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
Line 217:
 
</lang>
 
=={{header|ActionScript}}==
<lang actionscript>public function isNumeric(num:String):Boolean
Line 493 ⟶ 494:
<lang apl> ⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123'
1 1 0</lang>
 
 
=={{header|AppleScript}}==
Line 782:
123 -> isNumeric? true
12.34 -> isNumeric? true</pre>
 
 
=={{header|AutoHotkey}}==
Line 1,032 ⟶ 1,031:
</lang>
 
Assumes string is not empty.
 
=={{header|C}}==
Line 1,046 ⟶ 1,045:
strtod (s, &p);
return *p == '\0';
}</lang>
 
=={{header|C sharp|C#}}==
'''Framework:''' [[.NET]] 2.0+
 
<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
}</lang>
 
'''Framework:''' [[.NET]] 1.0+
 
<lang csharp>public static bool IsNumeric(string s)
{
try
{
Double.Parse(s);
return true;
}
catch
{
return false;
}
}</lang>
 
Line 1,098 ⟶ 1,127:
</lang>
 
=={{header|C sharp|C#CFScript}}==
ColdFusion Script (CfScript)
'''Framework:''' [[.NET]] 2.0+
<lang cfm>isNumeric(42)</lang>
 
<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
}</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}}==
Line 1,217 ⟶ 1,220:
console.log (isFinite(s) for s in [NaN, "fred", "###"]) # all false
</lang>
 
 
=={{header|ColdFusion}}==
Line 1,239 ⟶ 1,241:
===Alternative solution===
<lang><cfoutput>#isNumeric(42)#</cfoutput></lang>
 
=={{header|CFScript}}==
ColdFusion Script (CfScript)
<lang cfm>isNumeric(42)</lang>
 
=={{header|Common Lisp}}==
Line 1,327 ⟶ 1,325:
isNumeric("-0b10101"): false
isNumeric("0x10.5"): false</pre>
 
=={{header|Déjà Vu}}==
<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 )</lang>
{{out}}
<pre>"-3" true
"12ef" false
"12e3" true
"hello" false
"3.14" true
"0" true
"1" true</pre>
 
=={{header|Delphi}}==
Line 1,437 ⟶ 1,416:
var str = "1234567"
print(str.isNumeric())</lang>
 
=={{header|Déjà Vu}}==
<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 )</lang>
{{out}}
<pre>"-3" true
"12ef" false
"12e3" true
"hello" false
"3.14" true
"0" true
"1" true</pre>
 
=={{header|E}}==
Line 1,586 ⟶ 1,584:
For '-2.1e5': true
</pre>
 
 
=={{header|Forth}}==
Line 1,623 ⟶ 1,620:
is_numeric = e == 0
END FUNCTION is_numeric</lang>
 
=={{header|Free Pascal}}==
<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;</lang>
 
=={{header|FreeBASIC}}==
Line 1,740 ⟶ 1,757:
xyz (base 10) => false
</pre>
 
=={{header|Free Pascal}}==
<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;</lang>
 
=={{header|Gambas}}==
Line 2,062 ⟶ 2,059:
// javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}
</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:<lang jq>try tonumber catch false</lang>
Line 2,937 ⟶ 2,935:
 
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 6}}==
{{works with|Rakudo|2017.11}}
Perl 6 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 Perl 6, 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.
 
<lang perl6>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;</lang>
 
<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|Phix}}==
Line 3,301 ⟶ 3,246:
[1] TRUE TRUE FALSE
</lang>
 
=={{header|Racket}}==
<lang racket>(define (string-numeric? s) (number? (string->number s)))</lang>
Or, since all non-<tt>#f</tt> are true:
<lang racket>(define string-numeric? string->number)</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.11}}
Perl 6 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 Perl 6, 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.
 
<lang perl6>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;</lang>
 
<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}}==
Line 3,552 ⟶ 3,556:
string->number returns #f when the string is not numeric and otherwise the number, which is non-#f and therefore true.
<lang scheme>(define (numeric? s) (string->number s))</lang>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<lang sql pl>
--#SET TERMINATOR @
 
CREATE OR REPLACE FUNCTION IS_NUMERIC (
IN STRING VARCHAR(10)
) RETURNS SMALLINT
-- ) RETURNS BOOLEAN
BEGIN
DECLARE RET SMALLINT;
-- DECLARE RET BOOLEAN;
DECLARE TMP INTEGER;
DECLARE CONTINUE HANDLER FOR SQLSTATE '22018'
SET RET = 1;
-- SET RET = FALSE;
 
SET RET = 0;
--SET RET = TRUE;
SET TMP = INTEGER(STRING);
RETURN RET;
END @
 
VALUES IS_NUMERIC('5')@
VALUES IS_NUMERIC('0')@
VALUES IS_NUMERIC('-1')@
VALUES IS_NUMERIC('A')@
VALUES IS_NUMERIC('-')@
VALUES IS_NUMERIC('z')@
VALUES IS_NUMERIC('')@
VALUES IS_NUMERIC(' ')@
</lang>
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|Racket}}==
<lang racket>(define (string-numeric? s) (number? (string->number s)))</lang>
Or, since all non-<tt>#f</tt> are true:
<lang racket>(define string-numeric? string->number)</lang>
 
=={{header|Seed7}}==
Line 3,895 ⟶ 3,781:
if isnumeric(@s)=1 begin print 'Numeric' end
else print 'Non-numeric'</lang>
 
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<lang sql pl>
--#SET TERMINATOR @
 
CREATE OR REPLACE FUNCTION IS_NUMERIC (
IN STRING VARCHAR(10)
) RETURNS SMALLINT
-- ) RETURNS BOOLEAN
BEGIN
DECLARE RET SMALLINT;
-- DECLARE RET BOOLEAN;
DECLARE TMP INTEGER;
DECLARE CONTINUE HANDLER FOR SQLSTATE '22018'
SET RET = 1;
-- SET RET = FALSE;
 
SET RET = 0;
--SET RET = TRUE;
SET TMP = INTEGER(STRING);
RETURN RET;
END @
 
VALUES IS_NUMERIC('5')@
VALUES IS_NUMERIC('0')@
VALUES IS_NUMERIC('-1')@
VALUES IS_NUMERIC('A')@
VALUES IS_NUMERIC('-')@
VALUES IS_NUMERIC('z')@
VALUES IS_NUMERIC('')@
VALUES IS_NUMERIC(' ')@
</lang>
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}}==
Line 3,926 ⟶ 3,925:
 
Also <tt>string is integer</tt> (, <tt>string is alnum</tt> etc etc)
 
=={{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.
 
<lang toka>[ ( string -- flag )
>number nip ] is isNumeric
 
( Some tests )
decimal
" 100" isNumeric . ( succeeds, 100 is a valid decimal integer )
" 100.21" isNumeric . ( fails, 100.21 is not an integer)
" a" isNumeric . ( fails, 'a' is not a valid integer in the decimal base )
" $a" isNumeric . ( succeeds, because $ is a valid override prefix )
( denoting that the following character is a hexadecimal number )</lang>
 
=={{header|TMG}}==
Line 4,000 ⟶ 3,985:
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.
 
<lang toka>[ ( string -- flag )
>number nip ] is isNumeric
 
( Some tests )
decimal
" 100" isNumeric . ( succeeds, 100 is a valid decimal integer )
" 100.21" isNumeric . ( fails, 100.21 is not an integer)
" a" isNumeric . ( fails, 'a' is not a valid integer in the decimal base )
" $a" isNumeric . ( succeeds, because $ is a valid override prefix )
( denoting that the following character is a hexadecimal number )</lang>
 
=={{header|UNIX Shell}}==
10,343

edits