Determine if a string is numeric: Difference between revisions
added C translation to C++
(added C translation to C++) |
|||
(29 intermediate revisions by 21 users not shown) | |||
Line 32:
</pre>
The code:
<
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
Line 158:
db "1.000.000",0
TestString8:
db ".23456",0</
{{out}}
Line 200:
=={{header|8th}}==
<
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly Raspberry PI */
/* program strNumber.s */
Line 409:
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
Line 416:
The solution below uses conversion string to number and number to string to determine if the string is numeric.
{{libheader|Action! Tool Kit}}
<
BYTE FUNC AreEqual(CHAR ARRAY a,b)
Line 478:
Test("1.23BC")
Test("5.6.3")
RETURN</
=== Using a finite-state machine ===
The solution below uses a finite-state machine to determine if a string is numeric.
<
IF c='- OR c='+ THEN
RETURN (1)
Line 621:
Test("1.23BC")
Test("5.6.3")
RETURN</
{{out}}
Line 636:
=={{header|ActionScript}}==
<
{
return !isNaN(parseInt(num));
}</
=={{header|Ada}}==
The first file is the package interface containing the declaration of the Is_Numeric function.
<
function Is_Numeric (Item : in String) return Boolean;
end Numeric_Tests;</
The second file is the package body containing the implementation of the Is_Numeric function.
<
function Is_Numeric (Item : in String) return Boolean is
Dummy : Float;
Line 657:
return False;
end Is_Numeric;
end Numeric_Tests;</
The last file shows how the Is_Numeric function can be called.
<
with Numeric_Tests; use Numeric_Tests;
Line 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;</
{{out}}
<pre>
Line 679:
=={{header|Aime}}==
<
is_numeric(text s)
{
Line 696:
return 0;
}</
=={{header|ALGOL 68}}==
Line 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}}
<
BOOL out := TRUE;
PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE);
Line 731:
))
)
</syntaxhighlight>
{{out}}
<pre>
Line 740:
=={{header|ALGOL W}}==
<
% determnines whether the string contains an integer, real or imaginary %
Line 874:
testIsNumeric( " -.345LI", true );
end.</
{{out}}
<pre>
Line 896:
=={{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';
Line 905:
System.debug(decimalString.isNumeric()); // this will be false
System.debug(decimalString.remove('.').isNumeric()); // this will be true
</syntaxhighlight>
=={{header|APL}}==
{{works with|Dyalog APL}}
<
1 1 0</
Works with more recent versions of <B>Dyalog APL</B><
1 1 0
⊃⎕VFI '-' ⎕R '¯' ⊣ '152 -3.1415926 Foo123' ⍝ Simple: (ditto)
1 1 0</
{{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)
Line 980 ⟶ 986:
end script
end if
end mReturn</
{{Out}}
<
The classic way's slightly simpler, since the coercion result ''must'' be a real or an integer if the coercion itself didn't error.
<
if (s's class is not text) then return false
try
Line 995 ⟶ 1,001:
return false
end try
end isNumString</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 1,202 ⟶ 1,208:
</syntaxhighlight>
=={{header|Arturo}}==
<
print numeric? "1234"
print numeric? "1234 hello world"
print numeric? "12.34"
print numeric? "!#@$"
print numeric? "-1.23"</
{{out}}
Line 1,223 ⟶ 1,229:
=={{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.
<
Loop, Parse, list, %A_Space%
MsgBox,% IsNumeric(A_LoopField)
Line 1,234 ⟶ 1,240:
}
;Output: 1 1 1 0 1</
=={{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">
$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'
</syntaxhighlight>
{{out}}
<pre>
Line 1,247 ⟶ 1,253:
=={{header|BaCon}}==
<
IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN
Line 1,253 ⟶ 1,259:
ELSE
PRINT "Not a number"
ENDIF</
{{out}}
<pre>
Line 1,271 ⟶ 1,277:
=={{header|BASIC}}==
<
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</
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
#La función isNumeric() es nativa de BASIC256.
#Devuelve 1 (verdadero) si la expresión es un entero,
Line 1,307 ⟶ 1,313:
print s, " => "; isNumeric(s)
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,322 ⟶ 1,328:
==={{header|Commodore BASIC}}===
<
10 input "Enter a string";s$:gosub 1000:print
20 if r then print "You entered a number.":goto 99
Line 1,329 ⟶ 1,335:
1000 t1=val(s$):t1$=str$(t1)
1010 r=t1$=s$ or t1$=" "+s$
1099 return</
{{out}}
Line 1,346 ⟶ 1,352:
█</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.
Line 1,362 ⟶ 1,368:
Sleep
System
</syntaxhighlight>
{{out}}
<pre>
Line 1,379 ⟶ 1,385:
=={{header|Batch File}}==
<
if %a% == 0 (
if not "%arg%"=="0" (
Line 1,388 ⟶ 1,394:
) else (
echo Numeric.
)</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
READ N$
IF FN_isanumber(N$) THEN
Line 1,411 ⟶ 1,417:
IF LEFT$(A$,1) = "0" THEN = TRUE
= FALSE
</syntaxhighlight>
{{out}}
<pre>'PI' is NOT a number
Line 1,429 ⟶ 1,435:
=={{header|Befunge}}==
<
v _v# < < 0<
>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_ v
Line 1,438 ⟶ 1,444:
>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!v 0 > v
^ $< v < << ^_^#-"-"<
> "ciremuN">:#,_@ >>#$_"ciremun toN">:#,_@^ <</
Line 1,463 ⟶ 1,469:
'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'.
<
F
Line 1,477 ⟶ 1,486:
80000000000:~/#
S</
<
F
Line 1,507 ⟶ 1,516:
@("0.0000":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S</
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.
=={{header|Burlesque}}==
<
ps^^-]to{"Int""Double"}\/~[\/L[1==?*
</syntaxhighlight>
Assumes string is not empty.
Line 1,569 ⟶ 1,530:
Returns true (non-zero) if character-string parameter represents a signed or unsigned floating-point number. Otherwise returns false (zero).
<
#include <stdbool.h>
#include <stdlib.h>
bool isNumeric(const char *s) {
if (s == NULL || *s == '\0' || isspace(*s)) {
return
strtod(s, &p);
return *p == '\0';
}</
=={{header|C sharp|C#}}==
'''Framework:''' [[.NET]] 2.0+
<
{
double Result;
Line 1,593 ⟶ 1,556:
{
// do something
}</
'''Framework:''' [[.NET]] 1.0+
<
{
try
Line 1,608 ⟶ 1,571:
return false;
}
}</
=={{header|C++}}==
{{trans|C}}<syntaxhighlight lang="cpp">#include <cctype>
#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:
<
using namespace std;
Line 1,640 ⟶ 1,615:
return ( iss.rdbuf()->in_avail() == 0 );
}
</syntaxhighlight>
Using find:
<
bool isNumeric( const char* pszInput, int nNumberBase )
{
Line 1,651 ⟶ 1,626:
return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
}
</syntaxhighlight>
Using all_of (requires C++11)
<
bool isNumeric(const std::string& input) {
return std::all_of(input.begin(), input.end(), ::isdigit);
}
</syntaxhighlight>
=={{header|CFScript}}==
ColdFusion Script (CfScript)
<syntaxhighlight lang
=={{header|Clojure}}==
<
(if-let [s (seq s)]
(let [s (if (= (first s) \-) (next s) s)
Line 1,671 ⟶ 1,646:
s (if (= (first s) \.) (next s) s)
s (drop-while #(Character/isDigit %) s)]
(empty? s))))</
This works with any sequence of characters, not just Strings, e.g.:
<
Clojure has a fairly rich set of numeric literals, including Ratios, BigInts and BigDecimals. The Clojure reader will attempt to read any form starting with a digit (optionally preceded by a '+' or '-') as a number. So the following checks to see if such a read is successful:
<
(require '[clojure.edn :as edn])
(import [java.io PushbackReader StringReader])
Line 1,688 ⟶ 1,663:
; Check that the string has nothing after the number
(= -1 (.read reader)))))))
</syntaxhighlight>
<
user=> (number-string? "2r101010")
true
user=> (number-string? "22/7")
true
</syntaxhighlight>
=={{header|COBOL}}==
Line 1,700 ⟶ 1,675:
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.
<
procedure division.
display function test-numval-f("abc") end-display
Line 1,709 ⟶ 1,684:
display "failed numval-f test" end-display
end-if
goback.</
===Implementation===
{{works with|OpenCOBOL}}
<
PROGRAM-ID. Is-Numeric.
Line 1,766 ⟶ 1,741:
GOBACK
.</
=={{header|CoffeeScript}}==
The isFinite function is built into JavaScript, so we don't need to create our own function in 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>
=={{header|ColdFusion}}==
Adobe's ColdFusion
<
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
Line 1,792 ⟶ 1,767:
<cfelse>
is NOT Numeric.
</cfif></
===Alternative solution===
<syntaxhighlight lang="text"><cfoutput>#isNumeric(42)#</cfoutput></
=={{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.
<
(let ((*read-eval* nil))
(ignore-errors (numberp (read-from-string string)))))</
<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>.
<
(ignore-errors (parse-number:parse-number string))) ; parse failed, return false (nil)</
=={{header|D}}==
Line 1,811 ⟶ 1,786:
Using the standard Phobos function (currently binary and hex literals are not recognized):
<
void main() {
Line 1,819 ⟶ 1,794:
"-0b10101", "0x10.5"])
writefln(`isNumeric("%s"): %s`, s, s.strip().isNumeric(true));
}</
{{out}}
<pre>isNumeric("12"): true
Line 1,837 ⟶ 1,812:
===An Implementation===
<
bool isNumeric(in string s) pure {
Line 1,863 ⟶ 1,838:
"-0b10101", "0x10.5"])
writefln(`isNumeric("%s"): %s`, s, s.isNumeric);
}</
{{out}}
<pre>isNumeric("12"): true
Line 1,883 ⟶ 1,858:
This simple function is a wrapper around a built-in Delphi function
<syntaxhighlight lang="delphi">
function IsNumericString(const inStr: string): Boolean;
var
Line 1,890 ⟶ 1,865:
Result := TryStrToFloat(inStr,i);
end;
</syntaxhighlight>
This console application tests the function:
<syntaxhighlight lang="delphi">
program isNumeric;
Line 1,947 ⟶ 1,922:
end.
</syntaxhighlight>
{{out}} Example summarised:
Line 1,959 ⟶ 1,934:
=={{header|Dyalect}}==
<
try {
parse(this) is Integer or Float
Line 1,968 ⟶ 1,943:
var str = "1234567"
print(str.
=={{header|Déjà Vu}}==
<
true
try:
Line 1,979 ⟶ 1,954:
for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]:
!.( v is-numeric v )</
{{out}}
<pre>"-3" true
Line 1,990 ⟶ 1,965:
=={{header|E}}==
<
try {
<import:java.lang.makeDouble>.valueOf(specimen)
Line 1,997 ⟶ 1,972:
return false
}
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
func is_numeric a$ .
# because every variable must be used
h = h
return 1 - error
.
if is_numeric s$ = 1
print s$ & " is numeric"
print
.
</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
<
(string->number "albert")
→ #f
Line 2,025 ⟶ 2,000:
(if (string->number 666) 'YES 'NO)
→ YES
</syntaxhighlight>
=={{header|Elixir}}==
<
def is_numeric(str) do
case Float.parse(str) do
Line 2,037 ⟶ 2,012:
end
["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1)</
{{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>
Line 2,047 ⟶ 2,062:
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>.
<
Float = (catch erlang:list_to_float(L)),
Int = (catch erlang:list_to_integer(L)),
is_number(Float) orelse is_number(Int).</
=={{header|ERRE}}==
Short form using predeclared ERRE functions VAL and STR$.
<
PROGRAM NUMERIC
Line 2,070 ⟶ 2,085:
IF ANS% THEN PRINT("is num") ELSE PRINT("not num")
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>Enter a string? 12.30
Line 2,077 ⟶ 2,092:
=={{header|Euphoria}}==
<
function is_numeric(sequence s)
Line 2,083 ⟶ 2,098:
val = value(s)
return val[1]=GET_SUCCESS and atom(val[2])
end function</
=={{header|F_Sharp|F#}}==
<
=={{header|Factor}}==
<
=={{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">
class Main
{
Line 2,119 ⟶ 2,135:
}
}
</syntaxhighlight>
{{out}}
Line 2,128 ⟶ 2,144:
For '2a5': false
For '-2.1e5': true
</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}}
<
2dup snumber? ?dup if \ not standard, but >number is more cumbersome to use
0< if
Line 2,153 ⟶ 2,201:
hex
s" beef" is-numeric \ beef as integer = BEEF
s" &1234" is-numeric \ &1234 as integer = 4D2 ( decimal literal )</
=={{header|Fortran}}==
<
IMPLICIT NONE
CHARACTER(len=*), INTENT(IN) :: string
Line 2,164 ⟶ 2,212:
READ(string,*,IOSTAT=e) x
is_numeric = e == 0
END FUNCTION is_numeric</
=={{header|Free Pascal}}==
<
var
potentialInteger: integer;
Line 2,184 ⟶ 2,232:
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}}==
Line 2,193 ⟶ 2,302:
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.
<
Dim Shared symbols(0 To 15) As UByte
Line 2,287 ⟶ 2,396:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,301 ⟶ 2,410:
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}}==
<
Dim sAnswer, sString As String
Line 2,312 ⟶ 2,445:
Print sAnswer
End</
Output:
<pre>
Line 2,321 ⟶ 2,454:
=={{header|Go}}==
This uses a library function to meet the task's requirements:
<
import (
Line 2,339 ⟶ 2,472:
fmt.Printf(" %4s -> %t\n", s, isNumeric(s))
}
}</
{{out}}
Line 2,353 ⟶ 2,486:
This uses both a library function and a custom one but only checks for integerness:
<
import (
Line 2,380 ⟶ 2,513:
i := "one"
fmt.Printf(" %3s -> %t\n", i, isInt(i))
}</
{{out}}
Line 2,391 ⟶ 2,524:
=={{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.
<
def formatter = java.text.NumberFormat.instance
def pos = [0] as java.text.ParsePosition
Line 2,399 ⟶ 2,532:
// them the whole string was numeric
pos.index == it.size()
}</
Test Program:
<
println isNumeric('-.555')
println isNumeric('1,000,000')
println isNumeric(' 1 1 1 1 ')
println isNumeric('abcdef')</
{{out}}
Line 2,421 ⟶ 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):
<
[(_, "")] -> True
_ -> False
Line 2,430 ⟶ 2,563:
isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s</
One can easily add ''isRational'', ''isComplex'' etc. following the same pattern.
Line 2,436 ⟶ 2,569:
Another way would be to use the Data.Char module, allowing code such as:
<
isDigit selects ASCII digits i.e. '0'..'9'
isOctDigit selects '0'..'7'
isHexDigit selects '0'..'9','A'..'F','a'..'f'</
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. <
static function isNumeric(n:String):Bool
{
Line 2,456 ⟶ 2,589:
}
}
</syntaxhighlight>
=={{header|HicEst}}==
<
isNumeric("1001") ! 27 = 1 1 0 1 1 0
isNumeric("123") ! 26 = 0 1 0 1 1 0
Line 2,485 ⟶ 2,618:
isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L)
ENDIF
END</
=={{header|i}}==
<
number(n)
errors {
Line 2,503 ⟶ 2,636:
numeric("abcdefg")
numeric("1234test")
}</
=={{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">
write(image(x), if numeric(x) then " is numeric." else " is not numeric")
</syntaxhighlight>
=={{header|IDL}}==
<
on_ioerror, false
test = double(input)
return, 1
false: return, 0
end</
Could be called like this:
<
; ==> yes
if isnumeric('picklejuice') then print, 'yes' else print, 'no'
; ==> no</
=={{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}}==
<
isNumericScalar=: 1 -: isNumeric
TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents'
sayIsNumericScalar=: , TXT {::~ isNumericScalar</
Examples of use:
<
1
isNumeric '152 -3.1415926 Foo123'
Line 2,541 ⟶ 2,696:
0
sayIsNumericScalar '-3.1415926'
-3.1415926 represents a scalar numeric value.</
=={{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.
<
try {
Integer.parseInt(input);
Line 2,554 ⟶ 2,776:
return false;
}
}</
Alternative 1 : Check that each character in the string is number. Note that this will only works for integers.
<
if (s == null || s.isEmpty()) return false;
for (int x = 0; x < s.length(); x++) {
Line 2,567 ⟶ 2,789:
}
return true; // valid
}</
Alternative 2 : use a regular expression (a more elegant solution).
<
return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}</
Alternative 3 : use the positional parser in the java.text.NumberFormat object (a more robust solution). If, after parsing, the parse position is at the end of the string, we can deduce that the entire string was a valid number.
<
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(inputData, pos);
return inputData.length() == pos.getIndex();
}</
Alternative 4 : use the java.util.Scanner object. Very useful if you have to scan multiple entries.
<
Scanner sc = new Scanner(inputData);
return sc.hasNextInt();
}</
Scanner also has similar methods for longs, shorts, bytes, doubles, floats, BigIntegers, and BigDecimals as well as methods for integral types where you may input a base/radix other than 10 (10 is the default, which can be changed using the useRadix method).
=={{header|JavaScript}}==
A far better validator can be found on StackOverflow[http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric]
<
return !isNaN(parseFloat(n)) && isFinite(n);
}
Line 2,603 ⟶ 2,825:
//Or, in web browser in address field:
// javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}
</syntaxhighlight>
=={{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
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:
<
=={{header|Julia}}==
The function <tt>isnumber</tt> tests for strings that parse directly to numbers. This test excludes symbols, such as π 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.
<
isnumber(s::AbstractString) = tryparse(Float64, s) isa Number
Line 2,623 ⟶ 2,845:
fl = isnumber(t) ? "is" : "is not"
@printf("%35s %s a direct numeric literal.\n", t, fl)
end</
{{out}}
Line 2,645 ⟶ 2,867:
=={{header|Kotlin}}==
<
fun isNumeric(input: String): Boolean =
Line 2,658 ⟶ 2,880:
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"}")
}</
{{out}}
Line 2,677 ⟶ 2,899:
{{works with|Lasso|8 & 9 }}
<
string_isNumeric(#str) // true</
{{works with|Lasso|9}}
<
'1X34Q'->isdigit // false</
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
Line 2,743 ⟶ 2,965:
[NotNumber]
end function
</
=={{header|Lisaac}}==
<syntaxhighlight lang="lisaac">
"123457".is_integer.println;
// write TRUE on stdin
</syntaxhighlight>
=={{header|Logo}}==
<
=={{header|Lua}}==
This will also accept strings like "0xFF" or "314.16e-2" as numbers.
<
--it's a number
end;
</syntaxhighlight>
=={{header|M2000 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 {
Line 2,799 ⟶ 3,021:
Checkit
</syntaxhighlight>
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
Line 2,834 ⟶ 3,056:
Print isNumeric("1221.211.1221")=false, isNumeric("1221e1212")=false, isNumeric("1.2e4323")=false, isNumeric("-.122e-10")
</syntaxhighlight>
=={{header|Maple}}==
<
try
if type(parse(s), numeric) then
Line 2,847 ⟶ 3,069:
printf("The string is not numeric."):
end try:
end proc:</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}}==
<syntaxhighlight lang="matlab">
function r = isnum(a)
r = ~isnan(str2double(a))
Line 2,865 ⟶ 3,087:
disp(isnum("3.1415")) % 1
</syntaxhighlight>
=={{header|Maxima}}==
<
=={{header|MAXScript}}==
<
(
try
Line 2,880 ⟶ 3,102:
)
isNumeric "123"</
=={{header|min}}==
{{works with|min|0.19.3}}
<
dup (((int integer?) (pop false)) try) dip
((float float?) (pop false)) try or
) :numeric?</
=={{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.
<
return s == "0" or s == "-0" or val(s) != 0
end function
Line 2,899 ⟶ 3,121:
print isNumeric("-3.14157")
print isNumeric("5@*#!")
print isNumeric("spam")</
{{out}}
Line 2,909 ⟶ 3,131:
=={{header|MIPS Assembly}}==
<
# $a0 char val
# $a1 address pointer
Line 2,961 ⟶ 3,183:
li $a2,1
j loop
</syntaxhighlight>
=={{header|Mirah}}==
<
import java.text.ParsePosition
import java.util.Scanner
Line 3,088 ⟶ 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')</
=={{header|mIRC Scripting Language}}==
{{works with|mIRC}}
<
if (%value isnum) {
echo -s %value is numeric.
}</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt, Text;
Line 3,122 ⟶ 3,344:
IO.Put("isNumeric(-3.1415926) = " & Fmt.Bool(isNumeric("-3.1415926")) & "\n");
IO.Put("isNumeric(Foo123) = " & Fmt.Bool(isNumeric("Foo123")) & "\n");
END Numeric.</
{{out}}
Line 3,165 ⟶ 3,387:
=={{header|Nanoquery}}==
<
try
double(str)
Line 3,172 ⟶ 3,394:
return false
end
end</
=={{header|Nemerle}}==
<
using System.Console;
Line 3,193 ⟶ 3,415:
WriteLine($"$not is numeric: $(IsNumeric(not))");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 3,233 ⟶ 3,455:
]
return testData
</syntaxhighlight>
{{out}}
<pre>
Line 3,271 ⟶ 3,493:
=={{header|Nim}}==
<
proc isNumeric(s: string): bool =
Line 3,283 ⟶ 3,505:
for s in Strings:
echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric"</
We could prefer to use the “parsutils” module which avoids the exception:
<
proc isNumeric(s: string): bool =
Line 3,296 ⟶ 3,518:
for s in Strings:
echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric"</
{{out}}
Line 3,305 ⟶ 3,527:
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 3,313 ⟶ 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''.
<
NSLog( @"\"-123.4e5\" is numeric" );
else
Line 3,322 ⟶ 3,579:
NSLog( @"\"Not a number\" is not numeric" );
// prints: "-123.4e5" is numeric
// prints: "Not a number" is not numeric</
The following function can be used to check if a string is numeric "totally"; this is achieved by checking if the scanner reached the end of the string after the float is parsed.
<
{
NSScanner *sc = [NSScanner scannerWithString: s];
Line 3,334 ⟶ 3,591:
}
return NO;
}</
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).
<
{
NSUInteger len = [s length];
Line 3,363 ⟶ 3,620:
}
return (i == len) && status;
}</
Here we assumed that in the internal encoding of a string (that should be Unicode), 1 comes after 0, 2 after 1 and so on until 9. Another way could be to get the C String from the NSString object, and then the parsing would be the same of the one we could do in standard C, so this path is not given.
Line 3,373 ⟶ 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:
<
try ignore (int_of_string s); true
with _ -> false
Line 3,381 ⟶ 3,638:
with _ -> false
let is_numeric s = is_int s || is_float s</
=={{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.
<
if ( isnumeric(a) )
r = 1;
Line 3,399 ⟶ 3,656:
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1</
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
import "core:strconv"
import "core:fmt"
is_numeric :: proc(s: string) -> bool {
_, ok := strconv.parse_f32(s)
return ok
}
main :: proc() {
strings := []string{"1", "3.14", "-100", "1e2", "Inf", "rose"}
for s in strings {
fmt.println(s, "is", is_numeric(s) ? "numeric" : "not numeric")
}
}
/* Output:
1 is numeric
3.14 is numeric
-100 is numeric
1e2 is numeric
Inf is not numeric
rose is not numeric
*/</syntaxhighlight>
=={{header|Oz}}==
<
{String.isInt S} orelse {String.isFloat S}
end</
=={{header|PARI/GP}}==
<
my(t=type(eval(s)));
t == "t_INT" || t == "T_REAL"
};</
=={{header|Pascal}}==
Line 3,416 ⟶ 3,701:
=={{header|PeopleCode}}==
<syntaxhighlight lang="peoplecode">
Built-In Function
Syntax
Line 3,442 ⟶ 3,727:
/* do non-numeric processing */
End-if;
</syntaxhighlight>
=={{header|Perl}}==
{{works with|Perl|5.8}}
<
print looks_like_number($str) ? "numeric" : "not numeric\n";</
{{works with|Perl|5.8}}
Line 3,456 ⟶ 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]].
<
if (/^\d+\z/) { print "is a whole number\n" }
if (/^-?\d+\z/) { print "is an integer\n" }
Line 3,463 ⟶ 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" }</
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 3,469 ⟶ 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?''
<
use POSIX;
my $str = shift;
Line 3,483 ⟶ 3,768:
}
sub is_numeric { defined getnum($_[0]) }</
Or you could check out the String::Scanf module on the CPAN instead. The POSIX module (part of the standard Perl distribution) provides the "strtod" and "strtol" for converting strings to double and longs, respectively.
=={{header|Phix}}==
<!--<
<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>
<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>
Line 3,521 ⟶ 3,806:
<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>
<!--</
{{out}}
<pre>
Line 3,536 ⟶ 3,821:
=={{header|PHP}}==
<
$string = '123';
if(is_numeric(trim($string))) {
}
?></
=={{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
<
-> 123
Line 3,552 ⟶ 3,837:
: (format "-123.45" 4)
-> 1234500</
=={{header|Pike}}==
Line 3,558 ⟶ 3,843:
the %s before and after make sure the number is not surrounded by other text.
<syntaxhighlight lang="pike">
int(0..1) is_number(string s)
{
Line 3,571 ⟶ 3,856:
is_number(num);
-> true
</syntaxhighlight>
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
is_numeric: procedure (text) returns (bit (1));
declare text character (*);
Line 3,586 ⟶ 3,871:
done:
return ('0'b);
end is_numeric;</
<pre>
5 '1'B
Line 3,596 ⟶ 3,881:
=={{header|PL/SQL}}==
<
RETURN BOOLEAN
IS
Line 3,606 ⟶ 3,891:
WHEN others THEN
return( FALSE );
END;</
<
IF( IsNumeric( Value ) )
THEN
NULL;
END IF;</
=={{header|Plain English}}==
Line 3,621 ⟶ 3,906:
<code>If the string is any numeric literal,</code>
in this solution.
<
Start up.
Show whether "cat" is numeric.
Line 3,639 ⟶ 3,924:
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.</
{{out}}
<pre>
Line 3,657 ⟶ 3,942:
Note: PowerShell 1.0 does not support 'try'
THis simply tries arithmetic with the argument and if that fails, ''false'' is returned.
<
try {
0 + $x | Out-Null
Line 3,664 ⟶ 3,949:
return $false
}
}</
But this one doesn't work for strings like "8." though a . is appended it returns true!
Line 3,670 ⟶ 3,955:
Alternatively, you can use the static System.Int32.TryParse() method in the .NET framework.
<
$x2 = 0
$isNum = [System.Int32]::TryParse($x, [ref]$x2)
return $isNum
}</
=={{header|Prolog}}==
Line 3,681 ⟶ 3,966:
The code:
<
atom_string(Atom, String),
atom_number(Atom, _).</
A predicate to test the code:
<
forall( member(String, Strings),
( ( numeric_string(String)
Line 3,694 ⟶ 3,979:
format('~w is ~w number.~n', [String, Result])
)
).</
Example of using the test predicate:
<
123 is a number.
0.123 is a number.
Line 3,704 ⟶ 3,989:
NotNum is not a number.
1. is not a number.
true.</
=={{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.
<
#NotNumeric = #False
#IsNumeric = #True
Line 3,761 ⟶ 4,046:
Input()
CloseConsole()
EndIf</
{{out}}
<pre>'+3183.31151E+321' = 1
Line 3,770 ⟶ 4,055:
=={{header|Python}}==
===Python: Simple int/float===
<
try:
float(s)
Line 3,777 ⟶ 4,062:
return False
is_numeric('123.0')</
Or for positive integers only:
<syntaxhighlight lang
===Python: Most numeric literals===
Including complex, hex, binary, and octal numeric literals we get:
<
"""Return whether a literal can be parsed as a numeric value"""
castings = [int, float, complex,
Line 3,797 ⟶ 4,082:
except ValueError:
pass
return False</
Sample use, including value parsed, its type, and standard method str.isnumeric():
<
"""Return value of numeric literal or None if can't parse a value"""
castings = [int, float, complex,
Line 3,822 ⟶ 4,107:
for s in tests:
print("%14s -> %-14s %-20s is_numeric: %-5s str.isnumeric: %s" % (
'"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))</
{{out}}
<pre>
Line 3,855 ⟶ 4,140:
"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}}==
<
tuck over found iff
[ swap pluck drop ]
Line 3,871 ⟶ 4,163:
$ "152" task
$ "-3.1415926" task
$ "Foo123" task</
{{out}}
Line 3,881 ⟶ 4,173:
=={{header|R}}==
<
> suppressWarnings(!is.na(as.numeric(strings)))
[1] TRUE TRUE FALSE
</syntaxhighlight>
=={{header|Racket}}==
<
Or, since all non-<tt>#f</tt> are true:
<
=={{header|Raku}}==
Line 3,898 ⟶ 4,190:
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"
$term.Numeric !~~ Failure;
}
Line 3,911 ⟶ 4,203:
"<$_>", .&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;</
<pre> Coerce Don't coerce
Line 3,946 ⟶ 4,238:
=={{header|RapidQ}}==
<
$Typecheck on
Line 3,995 ⟶ 4,287:
showmessage (str$(isNumeric("-152.34","")))
end
</syntaxhighlight>
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
REBOL [
Title: "Is Numeric?"
Line 4,032 ⟶ 4,324:
} none
foreach x cases [print [x numeric? x pnumeric? x]]
</syntaxhighlight>
=={{header|Retro}}==
Retro does not have floating point numbers as part of the core system. For others, this can be done with:
<
=={{header|REXX}}==
<
yyy=' -123.78' /*or some such. */
Line 4,087 ⟶ 4,379:
/*note: REXX only looks at the first char for DATATYPE's 2nd argument.*/
/*note: some REXX interpreters don't support the ¬ (not) character. */</
=={{header|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}}==
<
begin
Float(s)
Line 4,104 ⟶ 4,400:
true # numeric
end
end</
or more compact:
<
!!Float(s) rescue false
end</
'''NB!''' Since Ruby 2.6 you no longer need `rescue`:
<
!!Float(s, exception: false)
end</
Adding `exception: false` will make it return `nil` instead.
'''sample'''
<
strings.each do |str|
puts "%9p => %s" % [str, is_numeric?(str)]
end</
{{out}}
<pre>
Line 4,140 ⟶ 4,436:
=={{header|Run BASIC}}==
<
print isNumeric("1ab")
Line 4,163 ⟶ 4,459:
[nxtDigit]
next i
END FUNCTION</
1ab 0</pre>
=={{header|Rust}}==
<
fn parsable<T: FromStr>(s: &str) -> bool {
s.parse::<T>().is_ok()
}</
=={{header|Scala}}==
<
import scala.util.control.Exception.allCatch
def isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
</syntaxhighlight>
<
def isNumeric(input: String): Boolean = input.forall(_.isDigit)
</syntaxhighlight>
Or a more complete version, using a complex regular expression:
<
def isNumeric2(str: String): Boolean = {
str.matches(s"""[+-]?((\d+(e\d+)?[lL]?)|(((\d+(\.\d*)?)|(\.\d+))(e\d+)?[fF]?))""")
}
</syntaxhighlight>
Or using the built-in number parsing and catching exceptions:
<
def isNumeric(str: String): Boolean = {
!throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble)
Line 4,199 ⟶ 4,495:
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.
<
=={{header|Seed7}}==
Line 4,209 ⟶ 4,505:
GetNumber reads a numeric literal from a string. The numeric literal is removed from the input string.
<
include "scanstri.s7i";
Line 4,220 ⟶ 4,516:
numberStri := getNumber(stri);
isNumeric := stri = "";
end func;</
=={{header|Sidef}}==
There is the the ''String.looks_like_number'' method, which returns true when a given strings looks like a number:
<
Alternatively, we can use regular expressions to determine this:
<
(s ~~ /^[+-]?+(?=\.?[0-9])[0-9_]*+(?:\.[0-9_]++)?(?:[Ee](?:[+-]?+[0-9_]+))?\z/) ||
(s ~~ /^0(?:b[10_]*|x[0-9A-Fa-f_]*|[0-9_]+\b)\z/)
}</
Sample:
<
for str in strings {
say ("%9s => %s" % (str, is_numeric(str)))
}</
{{out}}
<pre>
Line 4,255 ⟶ 4,551:
Simula uses the '&' instead of 'e' or 'E' for the exponent part of a floating point decimal number.
<
BOOLEAN PROCEDURE ISNUMERIC(W); TEXT W;
Line 4,329 ⟶ 4,625:
END
</syntaxhighlight>
{{out}}
<pre>
Line 4,358 ⟶ 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...
<
realIsNumeric [
(self first = $+) |
Line 4,377 ⟶ 4,673:
'-3.78.23'. "false"
'123e3' "false: the notation is not recognized"
} do: [ :a | a realIsNumeric printNl ]</
{{works with|Smalltalk/X}}
{{works with|GNU Smalltalk}}
(should work with all)
<
to handle radix numbers (such as 2r10111), use:
<
=={{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.
<
nchk convert(str,'real') :s(return)f(freturn)
nchk_end
Line 4,408 ⟶ 4,704:
output = isnum('abc')
output = isnum('A440')
end</
{{out}}
Line 4,422 ⟶ 4,718:
=={{header|SQL}}==
{{works with|MS SQL|Server 2005}}
<
set @s = '1234.56'
Line 4,428 ⟶ 4,724:
if isnumeric(@s)=1 begin print 'Numeric' end
else print 'Non-numeric'</
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<
--#SET TERMINATOR @
Line 4,462 ⟶ 4,758:
VALUES IS_NUMERIC('')@
VALUES IS_NUMERIC(' ')@
</syntaxhighlight>
Output:
<pre>
Line 4,544 ⟶ 4,840:
=={{header|Standard ML}}==
<
fun isInteger s = case Int.scan StringCvt.DEC Substring.getc (Substring.full s) of
SOME (_,subs) => Substring.isEmpty subs
Line 4,553 ⟶ 4,849:
| NONE => false
fun isNumeric s = isInteger s orelse isReal s</
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
return Double(a) != nil
}</
{{works with|Swift|1.x}}
This one only checks whether it is an integer:
<
return a.toInt() != nil
}</
=={{header|Tcl}}==
<
=={{header|TMG}}==
Unix TMG dialect. NOTE: the program also performs some basic normalization (namely, removing the plus sign and translating "E" to "e"):
<
parse(line)\prog
parse(error)\prog;
Line 4,591 ⟶ 4,887:
none: <<>>;
nonl: !<<
>>;</
Sample input:
Line 4,633 ⟶ 4,929:
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.
<
>number nip ] is isNumeric
Line 4,642 ⟶ 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 )</
=={{header|True BASIC}}==
{{trans|RapidQ}}
<
DECLARE FUNCTION isnumeric$
Line 4,710 ⟶ 5,006:
END FUNCTION
END
</syntaxhighlight>
=={{header|UNIX Shell}}==
<
#!/bin/bash
isnum() {
Line 4,736 ⟶ 5,032:
check 33.aa
check 3.3.3
</syntaxhighlight>
{{out}}
Line 4,749 ⟶ 5,045:
=={{header|Ursa}}==
<
try
double str
Line 4,756 ⟶ 5,052:
return false
end try
end isnum</
=={{header|VBA}}==
Line 4,762 ⟶ 5,058:
So we have to check the "." or "," and replace it by the Application.DecimalSeparator.
<
Debug.Print Is_Numeric("")
Debug.Print Is_Numeric("-5.32")
Line 4,777 ⟶ 5,073:
Other = IIf(Separat = ",", ".", ",")
Is_Numeric = IsNumeric(Replace(s, Other, Separat))
End Function</
=={{header|VBScript}}==
<syntaxhighlight lang
Returns a True if numeric and a false if not.
Line 4,788 ⟶ 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.
<
if (Num_Eval(SUPPRESS)==0 && Cur_Char != '0') {
Return(FALSE)
} else {
Return(TRUE)
}</
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2005}}
<
If IsNumeric(Value) Then
PRINT "It is numeric."
End If</
=={{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.
<
System.print("Are these strings numeric?")
Line 4,813 ⟶ 5,140:
var i = Num.fromString(s) // returns null if 's' is not numeric
System.print(" %(Fmt.s(4, s)) -> %((i != null) ? "yes" : "no")")
}</
{{out}}
Line 4,829 ⟶ 5,156:
=={{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'.
<
(IF (STRING->NUMBER X) T))</
=={{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}}==
<
try{ text.toInt(); True }
catch{ try{ text.toFloat(); True }
catch{ False }
}
}</
<pre>
isNum("123.4") //-->True
Line 4,850 ⟶ 5,440:
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: numeric
case: 1 input: '1' output: true
Line 4,858 ⟶ 5,448:
case: 5 input: 'Fred' output: false
case: 6 input: '' output: false
</syntaxhighlight>
=={{header|Zoea Visual}}==
|