Determine if a string is numeric: Difference between revisions
Line 300: | Line 300: | ||
string input = pszInput; |
string input = pszInput; |
||
return |
return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos); |
||
} |
} |
||
</lang> |
</lang> |
Revision as of 08:53, 5 July 2012
You are encouraged to solve this task according to the task description, using any language you may know.
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.
ActionScript
<lang actionscript>public function isNumeric(num:String):Boolean {
return !isNaN(parseInt(num));
}</lang>
Ada
The first file is the package interface containing the declaration of the Is_Numeric function. <lang ada>package Numeric_Tests is
function Is_Numeric (Item : in String) return Boolean;
end Numeric_Tests;</lang> The second file is the package body containing the implementation of the Is_Numeric function. <lang ada>package body Numeric_Tests is
function Is_Numeric (Item : in String) return Boolean is Dummy : Float; begin Dummy := Float'Value (Item); return True; exception when others => return False; end Is_Numeric;
end Numeric_Tests;</lang> The last file shows how the Is_Numeric function can be called. <lang ada>with Ada.Text_Io; use Ada.Text_Io; with Numeric_Tests; use Numeric_Tests;
procedure Is_Numeric_Test is
S1 : String := "152"; S2 : String := "-3.1415926"; S3 : String := "Foo123";
begin
Put_Line(S1 & " results in " & Boolean'Image(Is_Numeric(S1))); Put_Line(S2 & " results in " & Boolean'Image(Is_Numeric(S2))); Put_Line(S3 & " results in " & Boolean'Image(Is_Numeric(S3)));
end Is_Numeric_Test;</lang> The output of the program above is:
152 results in TRUE -3.1415926 results in TRUE Foo123 results in FALSE
ALGOL 68
<lang algol68>PROC is numeric = (REF STRING string) BOOL: (
BOOL out := TRUE; PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE);
FILE memory; associate(memory, string); on value error(memory, call back false); on logical file end(memory, call back false);
UNION (INT, REAL, COMPL) numeric:=0.0; # use a FORMAT pattern instead of a regular expression # getf(memory, ($gl$, numeric)); out
);
test:(
STRING s1 := "152", s2 := "-3.1415926", s3 := "Foo123"; print(( s1, " results in ", is numeric(s1), new line, s2, " results in ", is numeric(s2), new line, s3, " results in ", is numeric(s3), new line ))
) </lang> Output:
152 results in T -3.1415926 results in T Foo123 results in F
APL
<lang apl> ⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123' 1 1 0</lang>
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. <lang autohotkey>list = 0 .14 -5.2 ten 0xf Loop, Parse, list, %A_Space%
MsgBox,% IsNumeric(A_LoopField)
Return
IsNumeric(x) {
If x is number Return, 1 Else Return, 0
}
- Output
- 1 1 1 0 1</lang>
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: <lang AWK>$ awk 'function isnum(x){return(x==x+0)}BEGIN{print isnum("hello"),isnum("-42")}' 0 1</lang>
BASIC
<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</lang>
BBC BASIC
<lang bbcbasic> REPEAT
READ N$ IF FN_isanumber(N$) THEN PRINT "'" N$ "' is a number" ELSE PRINT "'" N$ "' is NOT a number" ENDIF UNTIL N$ = "end" END DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0" DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end" DEF FN_isanumber(A$) ON ERROR LOCAL = FALSE IF EVAL("(" + A$ + ")") <> VAL(A$) THEN = FALSE IF VAL(A$) <> 0 THEN = TRUE IF LEFT$(A$,1) = "0" THEN = TRUE = FALSE
</lang> Output:
'PI' is NOT a number '0123' is a number '-0123' is a number '12.30' is a number '-12.30' is a number '123!' is NOT a number '0' is a number '0.0' is a number '.123' is a number '-.123' is a number '12E3' is a number '12E-3' is a number '12+3' is NOT a number 'end' is NOT a number
Bracmat
To check whether a string is a number, a fraction or an integer, use the patterns #
, /
and ~/#
("not a fraction and yet a number"). In the pattern matching examples below (which can be typed in at the Bracmat prompt) F
denotes 'failure' and S
denotes 'success'.
<lang bracmat>43257349578692:/
F
260780243875083/35587980:/
S
247/30:~/#
F
80000000000:~/#
S</lang>
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 the pattern ~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#)
recognises string representations of floating point numbers.
<lang bracmat>@("1.000-4E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
F
@("1.0004E-54328":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("-464641.0004E-54328":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("1/2.0004E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
F
@("1357E-10":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("1357e0":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("13579":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("1.246":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("0.0":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S
@("0.0000":~/# (|"." (|? 0|`) (|~/#:>0)) (|(E|e) ~/#))
S</lang>
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
);
( out$float2fraction$"1.2" & out$float2fraction$"1.02" & out$float2fraction$"1.01" & out$float2fraction$"10.01" & out$float2fraction$"10.01e10" & 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:
6/5 51/50 101/100 1001/100 100100000000 1001/10 1001 1001/10000 -1001/10000 -1/10 0
C
Returns true (non-zero) if character-string parameter represents a signed or unsigned floating-point number. Otherwise returns false (zero).
<lang c>#include <ctype.h>
- include <stdlib.h>
int isNumeric (const char * s) {
if (s == NULL || *s == '\0' || isspace(*s)) return 0; char * p; strtod (s, &p); return *p == '\0';
}</lang>
C++
<lang cpp>#include <sstream> // for istringstream
using namespace std;
bool isNumeric( const char* pszInput, int nNumberBase ) { istringstream iss( pszInput );
if ( nNumberBase == 10 ) { double dTestSink; iss >> dTestSink; } else if ( nNumberBase == 8 || nNumberBase == 16 ) { int nTestSink; iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink; } else return false;
// was any input successfully consumed/converted? if ( ! iss ) return false;
// was all the input successfully consumed/converted? return ( iss.rdbuf()->in_avail() == 0 ); }
/* OR */
bool isNumeric( const char* pszInput, int nNumberBase ) { string base = "0123456789ABCDEF"; string input = pszInput;
return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos); } </lang>
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>
Clojure
<lang lisp>(defn numeric? [s]
(if-let [s (seq s)] (let [s (if (= (first s) \-) (next s) s) s (drop-while #(Character/isDigit %) s) s (if (= (first s) \.) (next s) s) s (drop-while #(Character/isDigit %) s)] (empty? s))))</lang>
This works with any sequence of characters, not just Strings, e.g.: <lang lisp>(numeric? [\1 \2 \3]) ;; yields logical true</lang>
CoffeeScript
The isFinite function is built into JavaScript, so we don't need to create our own function in CoffeeScript. <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 </lang>
ColdFusion
Adobe's ColdFusion
<lang cfm><cfset TestValue=34>
TestValue: <cfoutput>#TestValue#</cfoutput>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif>
<cfset TestValue="NAS">
TestValue: <cfoutput>#TestValue#</cfoutput>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif></lang>
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. <lang lisp>(defun numeric-string-p (string)
(let ((*read-eval* nil)) (ignore-errors (numberp (read-from-string string)))))</lang>
ignore-errors
here handles returning nil in case the input is invalid rather than simply non-numeric.
However, read
[-from-string
] has the side effect of interning any symbols encountered, and can have memory allocation larger than the input size (due to read syntax such as #*
, which takes a length). The parse-number
library provides a numbers-only equivalent of read
.
<lang lisp>(defun numeric-string-p (string)
(handler-case (progn (parse-number:parse-number string) t) ; parse succeeded, discard it and return true (t) (parse-number::invalid-number () nil))) ; parse failed, return false (nil)</lang>
D
<lang d>import std.stdio, std.string, std.conv;
bool isNumeric(in string s) /*pure nothrow*/ {
try to!real(s.strip()); catch (ConvException e) return false; return true;
}
void main() {
foreach (s; ["12", " 12\t", "hello12", "-12", "02", "0-12", "+12", "1.5"]) writefln(`isNumeric("%s") = %s`, s, isNumeric(s));
writeln("\nCurrently no hex or binary conversion:"); foreach (s; ["0x10", "6b"]) writefln(`isNumeric("%s") = %s`, s, isNumeric(s));
}</lang>
- Output:
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 Currently no hex or binary conversion: isNumeric("0x10") = false isNumeric("6b") = false
Delphi
This simple function is a wrapper around a built-in Delphi function
<lang Delphi> function IsNumericString(const inStr: string): Boolean; var
i: extended;
begin
Result := TryStrToFloat(inStr,i);
end; </lang>
This console application tests the function:
<lang Delphi> program isNumeric;
{$APPTYPE CONSOLE}
uses
Classes, SysUtils;
function IsNumericString(const inStr: string): Boolean; var
i: extended;
begin
Result := TryStrToFloat(inStr,i);
end;
{ Test function }
var
s: string; c: Integer;
const
MAX_TRIES = 10; sPROMPT = 'Enter a string (or type "quit" to exit):'; sIS = ' is numeric'; sISNOT = ' is NOT numeric';
begin
c := 0; s := ; repeat Inc(c); Writeln(sPROMPT); Readln(s); if (s <> ) then begin tmp.Add(s); if IsNumericString(s) then begin Writeln(s+sIS); end else begin Writeln(s+sISNOT); end; Writeln(); end; until (c >= MAX_TRIES) or (LowerCase(s) = 'quit');
end.
</lang>
Example summarised output:
123 is numeric -123.456 is numeric -123.-456 is NOT numeric .345 is numeric m1k3 is NOT numeric
E
<lang e>def isNumeric(specimen :String) {
try { <import:java.lang.makeDouble>.valueOf(specimen) return true } catch _ { return false }
}</lang>
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 is_number/1, which will return true if the argument passed is either an integer or a float. Erlang also has two functions to transform a string to either a floating number or an integer, which will be used in conjunction with is_number/1.
<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).</lang>
Euphoria
<lang Euphoria>include get.e
function is_numeric(sequence s)
sequence val val = value(s) return val[1]=GET_SUCCESS and atom(val[2])
end function</lang>
F#
<lang fsharp>let is_numeric a = fst (System.Double.TryParse(a))</lang>
Factor
<lang factor>: numeric? ( string -- ? ) string>number >boolean ;</lang>
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.
<lang fantom> class Main {
// function to see if str contains a number of any of built-in types static Bool readNum (Str str) { int := Int.fromStr (str, 10, false) // use base 10 if (int != null) return true float := Float.fromStr (str, false) if (float != null) return true decimal := Decimal.fromStr (str, false) if (decimal != null) return true
return false }
public static Void main () { echo ("For '2': " + readNum ("2")) echo ("For '-2': " + readNum ("-2")) echo ("For '2.5': " + readNum ("2.5")) echo ("For '2a5': " + readNum ("2a5")) echo ("For '-2.1e5': " + readNum ("-2.1e5")) }
} </lang>
Output:
For '2': true For '-2': true For '2.5': true For '2a5': false For '-2.1e5': true
Forth
<lang forth>: is-numeric ( addr len -- )
2dup snumber? ?dup if \ not standard, but >number is more cumbersome to use 0< if -rot type ." as integer = " . else 2swap type ." as double = " <# #s #> type then else 2dup >float if type ." as float = " f. else type ." isn't numeric in base " base @ dec. then then ;
s" 1234" is-numeric \ 1234 as integer = 1234 s" 1234." is-numeric \ 1234. as double = 1234 s" 1234e" is-numeric \ 1234e as float = 1234. s" $1234" is-numeric \ $1234 as integer = 4660 ( hex literal ) s" %1010" is-numeric \ %1010 as integer = 10 ( binary literal ) s" beef" is-numeric \ beef isn't numeric in base 10 hex s" beef" is-numeric \ beef as integer = BEEF s" &1234" is-numeric \ &1234 as integer = 4D2 ( decimal literal )</lang>
Fortran
<lang fortran>FUNCTION is_numeric(string)
IMPLICIT NONE CHARACTER(len=*), INTENT(IN) :: string LOGICAL :: is_numeric REAL :: x INTEGER :: e READ(string,*,IOSTAT=e) x is_numeric = e == 0
END FUNCTION is_numeric</lang>
Go
<lang go>import "strconv"
func IsNumeric(s string) bool {
_, err := strconv.ParseFloat(s, 64) return err == nil
}</lang>
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. <lang groovy>def isNumeric = {
def formatter = java.text.NumberFormat.instance def pos = [0] as java.text.ParsePosition formatter.parse(it, pos) // if parse position index has moved to end of string // them the whole string was numeric pos.index == it.size()
}</lang>
Test Program: <lang groovy>println isNumeric('1') println isNumeric('-.555') println isNumeric('1,000,000') println isNumeric(' 1 1 1 1 ') println isNumeric('abcdef')</lang>
Output:
true true true false false
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.
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):
<lang haskell>isInteger s = case reads s :: [(Integer, String)] of
[(_, "")] -> True _ -> False
isDouble s = case reads s :: [(Double, String)] of
[(_, "")] -> True _ -> False
isNumeric :: String -> Bool isNumeric s = isInteger s || isDouble s</lang>
One can easily add isRational, isComplex etc. following the same pattern.
Another way would be to use the Data.Char module, allowing code such as:
<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'</lang>
so read s::Int (for instance) could be reliably used if string s passed these tests.
HicEst
<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 isNumeric("1E78") ! 48 = 0 0 0 0 1 1 isNumeric("-0.123") ! 4 = 0 0 1 0 0 1 isNumeric("-123.456e-78") ! 32 = 0 0 0 0 0 1 isNumeric(" 123") ! 0: leading blank isNumeric("-123.456f-78") ! 0: illegal character f
FUNCTION isNumeric(string) ! true ( > 0 ), no leading/trailing blanks
CHARACTER string b = INDEX(string, "[01]+", 128, Lbin) ! Lbin returns length found i = INDEX(string, "-?\d+", 128, Lint) ! regular expression: 128 f = INDEX(string, "-?\d+\.\d*", 128, Lflt) o = INDEX(string, "[0-7]+", 128, Loct) h = INDEX(string, "[0-9A-F]+", 128, Lhex) ! case sensitive: 1+128 s = INDEX(string, "-?\d+\.*\d*E[+-]*\d*", 128, Lsci) IF(anywhere) THEN ! 0 (false) by default isNumeric = ( b > 0 ) + 2*( i > 0 ) + 4*( f > 0 ) + 8*( o > 0 ) + 16*( h > 0 ) + 32*( s > 0 ) ELSEIF(boolean) THEN ! 0 (false) by default isNumeric = ( b + i + f + o + h + s ) > 0 ! this would return 0 or 1 ELSE L = LEN(string) isNumeric = (Lbin==L) + 2*(Lint==L) + 4*(Lflt==L) + 8*(Loct==L) + 16*(Lhex==L) + 32*(Lsci==L) ENDIF END</lang>
Icon and 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. <lang Icon> write(image(x), if numeric(x) then " is numeric." else " is not numeric") </lang>
IDL
<lang idl>function isnumeric,input
on_ioerror, false test = double(input) return, 1 false: return, 0
end</lang>
Could be called like this:
<lang idl>if isnumeric('-123.45e-2') then print, 'yes' else print, 'no'
- ==> yes
if isnumeric('picklejuice') then print, 'yes' else print, 'no'
- ==> no</lang>
J
<lang j>isNumeric=: _ ~: _ ". ] isNumericScalar=: 1 -: isNumeric TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents' sayIsNumericScalar=: , TXT {::~ isNumericScalar</lang> Examples of use: <lang j> isNumeric '152' 1
isNumeric '152 -3.1415926 Foo123'
1 1 0
isNumeric '42 foo42 4.2e1 4200e-2 126r3 16b2a 42foo'
1 0 1 1 1 1 0
isNumericScalar '152 -3.1415926 Foo123'
0
sayIsNumericScalar '-3.1415926'
-3.1415926 represents a scalar numeric value.</lang>
Java
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. <lang java>public boolean isNumeric(String input) {
try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { // s is not numeric return false; }
}</lang>
Alternative 1 : Check that each character in the string is number. Note that this will only works for integers.
<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++) { final char c = s.charAt(x); if (x == 0 && (c == '-')) continue; // negative if ((c >= '0') && (c <= '9')) continue; // 0 - 9 return false; // invalid } return true; // valid
}</lang>
Alternative 2 : use a regular expression (a more elegant solution).
<lang java>public static boolean isNumeric(String inputData) {
return inputData.matches("[-+]?\\d+(\\.\\d+)?");
}</lang>
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.
<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();
}</lang>
Alternative 4 : use the java.util.Scanner object. Very useful if you have to scan multiple entries.
<lang java>public static boolean isNumeric(String inputData) {
Scanner sc = new Scanner(inputData); return sc.hasNextInt();
}</lang> 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).
JavaScript
<lang javascript>var value = "123.45e7"; // Assign string literal to value if (isFinite(value)) {
// value is a number
} //Or, in web browser in address field: // javascript:value="123.45e4"; if(isFinite(value)) {alert('numeric')} else {alert('non-numeric')} </lang>
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lasso
<lang Lasso>var('str'='12345'); if( string_isNumeric($str) );
('Yes, it is numeric.');
/if;</lang>
Liberty BASIC
<lang lb> DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0" DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
while n$ <> "end"
read n$ print n$, IsNumber(n$)
wend end
function IsNumber(string$)
on error goto [NotNumber] string$ = trim$(string$) 'check for float overflow n = val(string$)
'assume it is number and try to prove wrong IsNumber = 1 for i = 1 to len(string$) select case mid$(string$, i, 1) case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" HasNumeric = 1 'to check if there are any digits case "e", "E" '"e" must not occur more than once 'must not occur before digits
if HasE > 0 or HasNumeric = 0 then IsNumber = 0 exit for end if HasE = i 'store position of "e" HasNumeric = 0 'needs numbers after "e" case "-", "+" 'must be either first character or immediately after "e" '(HasE = 0 if no occurrences yet) if HasE <> i-1 then IsNumber = 0 exit for end if case "." 'must not have previous points and must not come after "e" if HasE <> 0 or HasPoint <> 0 then IsNumber = 0 exit for end if HasPoint = 1 case else 'no other characters allowed IsNumber = 0 exit for end select next i 'must have digits if HasNumeric = 0 then IsNumber = 0 [NotNumber]
end function
</lang>
Lisaac
<lang Lisaac> "123457".is_integer.println; // write TRUE on stdin </lang>
Logo
<lang logo>show number? "-1.23 ; true</lang>
Lua
This will also accept strings like "0xFF" or "314.16e-2" as numbers. <lang lua>if tonumber(a) ~= nil then
--it's a number
end; </lang>
Mathematica
<lang Mathematica>NumberQ[ToExpression["02553352000242"]]</lang>
MATLAB
This can be done using several methods in MATLAB. One of the possible ways is given below. An important note, the strings 'i' and 'j' will be recognized as imaginary numbers, not as strings containing the letters 'i' and 'j'; furthermore function names which evaluate to numeric output (ie, 'white') will be miscategorized as numeric. Please also note the use of Matlab's '~' character, which is the NOT command in Matlab.
<lang MATLAB>>> ~isempty(str2num('32.10'))
ans =
1 %Is a numeric string
>> ~isempty(str2num('jh'))
ans =
0 %Is a character string
>> ~isempty(str2num('32i'))
ans =
1 %Is a numeric string
>> ~isempty(str2num('white'))
ans =
1 %Suggests that 'white' is a numeric string</lang>
A second approach is as follows: <lang MATLAB> >> numericCharacters = '0123456789ij.-'; >> all(ismember('3.1415',numericCharacters))
ans =
1 %Is a numeric string
>> all(ismember('white',numericCharacters))
ans =
0 %Properly detects that 'white' is not a numeric string
>> all(ismember('[1,2,3]',numericCharacters))
ans =
0 %Does not handle vector/array input; though could be adjusted by changing numericCharacters</lang>
MAXScript
<lang maxscript>fn isNumeric str = (
try ( (str as integer) != undefined ) catch(false)
)
isNumeric "123"</lang>
Mirah
<lang mirah>import java.text.NumberFormat import java.text.ParsePosition import java.util.Scanner
- this first example relies on catching an exception,
- which is bad style and poorly performing in Java
def is_numeric?(s:string)
begin Double.parseDouble(s) return true rescue return false end
end
puts '123 is numeric' if is_numeric?('123') puts '-123 is numeric' if is_numeric?('-123') puts '123.1 is numeric' if is_numeric?('123.1')
puts 'nil is not numeric' unless is_numeric?(nil) puts " is not numeric" unless is_numeric?() puts 'abc is not numeric' unless is_numeric?('abc') puts '123- is not numeric' unless is_numeric?('123-') puts '1.2.3 is not numeric' unless is_numeric?('1.2.3')
- check every element of the string
def is_numeric2?(s: string)
if (s == nil || s.isEmpty()) return false end if (!s.startsWith('-')) if s.contains('-') return false end end 0.upto(s.length()-1) do |x| c = s.charAt(x) if ((x == 0) && (c == '-'.charAt(0))) # negative number elsif (c == '.'.charAt(0)) if (s.indexOf('.', x) > -1) return false # more than one period end elsif (!Character.isDigit(c)) return false end end true
end
puts '123 is numeric' if is_numeric2?('123')
puts '-123 is numeric' if is_numeric2?('-123')
puts '123.1 is numeric' if is_numeric2?('123.1')
puts 'nil is not numeric' unless is_numeric2?(nil) puts " is not numeric" unless is_numeric2?() puts 'abc is not numeric' unless is_numeric2?('abc') puts '123- is not numeric' unless is_numeric2?('123-') puts '1.2.3 is not numeric' unless is_numeric2?('1.2.3')
- use a regular expression
def is_numeric3?(s:string)
s == nil || s.matches("[-+]?\\d+(\\.\\d+)?")
end
puts '123 is numeric' if is_numeric3?('123') puts '-123 is numeric' if is_numeric3?('-123') puts '123.1 is numeric' if is_numeric3?('123.1')
puts 'nil is not numeric' unless is_numeric3?(nil) puts " is not numeric" unless is_numeric3?() puts 'abc is not numeric' unless is_numeric3?('abc') puts '123- is not numeric' unless is_numeric3?('123-') puts '1.2.3 is not numeric' unless is_numeric3?('1.2.3')
- use the positional parser in the java.text.NumberFormat object
- (a more robust solution). If, after parsing, the parse position is at
- the end of the string, we can deduce that the entire string was a
- valid number.
def is_numeric4?(s:string)
return false if s == nil formatter = NumberFormat.getInstance() pos = ParsePosition.new(0) formatter.parse(s, pos) s.length() == pos.getIndex()
end
puts '123 is numeric' if is_numeric4?('123')
puts '-123 is numeric' if is_numeric4?('-123')
puts '123.1 is numeric' if is_numeric4?('123.1')
puts 'nil is not numeric' unless is_numeric4?(nil) puts " is not numeric" unless is_numeric4?() puts 'abc is not numeric' unless is_numeric4?('abc') puts '123- is not numeric' unless is_numeric4?('123-') puts '1.2.3 is not numeric' unless is_numeric4?('1.2.3')
- use the java.util.Scanner object. Very useful if you have to
- scan multiple entries. Scanner also has similar methods for longs,
- shorts, bytes, doubles, floats, BigIntegers, and BigDecimals as well
- as methods for integral types where you may input a base/radix other than
- 10 (10 is the default, which can be changed using the useRadix method).
def is_numeric5?(s:string)
return false if s == nil Scanner sc = Scanner.new(s) sc.hasNextDouble()
end
puts '123 is numeric' if is_numeric5?('123') puts '-123 is numeric' if is_numeric5?('-123') puts '123.1 is numeric' if is_numeric5?('123.1')
puts 'nil is not numeric' unless is_numeric5?(nil) puts " is not numeric" unless is_numeric5?() puts 'abc is not numeric' unless is_numeric5?('abc') puts '123- is not numeric' unless is_numeric5?('123-') puts '1.2.3 is not numeric' unless is_numeric5?('1.2.3')</lang>
mIRC Scripting Language
<lang mirc>var %value = 3 if (%value isnum) {
echo -s %value is numeric.
}</lang>
Modula-3
<lang modula3>MODULE Numeric EXPORTS Main;
IMPORT IO, Fmt, Text;
PROCEDURE isNumeric(s: TEXT): BOOLEAN =
BEGIN FOR i := 0 TO Text.Length(s) DO WITH char = Text.GetChar(s, i) DO IF i = 0 AND char = '-' THEN EXIT; END; IF char >= '0' AND char <= '9' THEN EXIT; END; RETURN FALSE; END; END; RETURN TRUE; END isNumeric;
BEGIN
IO.Put("isNumeric(152) = " & Fmt.Bool(isNumeric("152")) & "\n"); IO.Put("isNumeric(-3.1415926) = " & Fmt.Bool(isNumeric("-3.1415926")) & "\n"); IO.Put("isNumeric(Foo123) = " & Fmt.Bool(isNumeric("Foo123")) & "\n");
END Numeric.</lang>
Output:
isNumeric(152) = TRUE isNumeric(-3.1415926) = TRUE isNumeric(Foo123) = FALSE
MUMPS
In MUMPS, strings are automatically converted to numbers when a unary or binary arithmetic operator works upon them. If there are no leading digits, a string converts to zero. If there a string of digits followed by an "e" or an "E" followed in turn by more digits, the numbers after the letter are treated as an exponent.
Examples from command line:
USER>WRITE +"1" 1 USER>WRITE +"1A" 1 USER>WRITE +"A1" 0 USER>WRITE +"1E" 1 USER>WRITE +"1E2" 100 USER>WRITE +"1EA24" 1 USER>WRITE +"1E3A" 1000 USER>WRITE +"1E-3" .001
There is a function, $ISVALIDNUM, to do the testing.
USER>WRITE $SELECT($ISVALIDNUM("123"):"Valid",1:"Invalid"),! Valid USER>WRITE $SELECT($ISVALIDNUM("a123"):"Valid",1:"Invalid"),! Invalid USER>WRITE $SELECT($ISVALIDNUM("123a"):"Valid",1:"Invalid"),! Invalid USER>WRITE $SELECT($ISVALIDNUM("123e4"):"Valid",1:"Invalid"),! Valid
Nemerle
<lang Nemerle>using System; using System.Console;
module IsNumeric {
IsNumeric( input : string) : bool { mutable meh = 0.0; // I don't want it, not going to use it, why force me to declare it? double.TryParse(input, out meh) } Main() : void { def num = "-1.2345E6"; def not = "abc45"; WriteLine($"$num is numeric: $(IsNumeric(num))"); WriteLine($"$not is numeric: $(IsNumeric(not))"); }
}</lang>
Objective-C
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.
<lang objc>if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] ) NSLog( @"\"-123.4e5\" is numeric" ); else NSLog( @"\"-123.4e5\" is not numeric" ); if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL] ) NSLog( @"\"Not a number\" is numeric" ); else NSLog( @"\"Not a number\" is not numeric" ); // prints: "-123.4e5" is numeric // prints: "Not a number" is not numeric</lang>
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.
<lang objc>BOOL isNumeric(NSString *s) {
NSScanner *sc = [NSScanner scannerWithString: s]; if ( [sc scanFloat:NULL] ) { return [sc isAtEnd]; } return NO;
}</lang>
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).
<lang objc>BOOL isNumericI(NSString *s) {
NSUInteger len = [s length]; NSUInteger i; BOOL status = NO; for(i=0; i < len; i++) { unichar singlechar = [s characterAtIndex: i]; if ( (singlechar == ' ') && (!status) ) { continue; } if ( ( singlechar == '+' || singlechar == '-' ) && (!status) ) { status=YES; continue; } if ( ( singlechar >= '0' ) && ( singlechar <= '9' ) ) { status = YES; } else { return NO; } } return (i == len) && status;
}</lang>
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.
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.
The task doesn't define which strings are considered "numeric", so we do ints and floats, which should catch the most common cases:
<lang ocaml>let is_int s =
try ignore (int_of_string s); true with _ -> false
let is_float s =
try ignore (float_of_string s); true with _ -> false
let is_numeric s = is_int s || is_float s</lang>
Octave
The builtin function isnumeric return true (1) if the argument is a data of type number; the provided function isnum 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.
<lang octave>function r = isnum(a)
if ( isnumeric(a) ) r = 1; else o = str2num(a); r = !isempty(o); endif
endfunction
% tests disp(isnum(123)) % 1 disp(isnum("123")) % 1 disp(isnum("foo123")) % 0 disp(isnum("123bar")) % 0 disp(isnum("3.1415")) % 1</lang>
STR2NUM uses internally the function eval(), therefore it should not be used for unsecured data (e.g. user input). Use instead str2double() or scanf().
<lang octave>function r = isnum(a)
if ( isnumeric(a) ) r = 1; else o = str2double(a); r = !isnan(o); endif
endfunction</lang>
Oz
<lang oz>fun {IsNumeric S}
{String.isInt S} orelse {String.isFloat S}
end</lang>
PARI/GP
<lang parigp>isNumeric(s)={
my(t=type(eval(s))); t == "t_INT" || t == "T_REAL"
};</lang>
Pascal
<lang pascal>function IsNumeric(Value: string; const AllowFloat: Boolean): Boolean; var
ValueInt: Integer; ValueFloat: Extended; ErrCode: Integer;
begin // Check for integer: Val only accepts integers when passed integer param Value := SysUtils.Trim(Value); Val(Value, ValueInt, ErrCode); Result := ErrCode = 0; // Val sets error code 0 if OK if not Result and AllowFloat then
begin // Check for float: Val accepts floats when passed float param Val(Value, ValueFloat, ErrCode); Result := ErrCode = 0; // Val sets error code 0 if OK end;
end;</lang>
Perl
<lang perl>use Scalar::Util qw(looks_like_number); print looks_like_number($str) ? "numeric" : "not numeric\n";</lang>
Quoting from perlfaq4:
How do I determine whether a scalar is a number/whole/integer/float?
Assuming that you don't care about IEEE notations like "NaN" or "Infinity", you probably just want to use a regular expression.
<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" } if (/^[+-]?\d+\z/) { print "is a +/- integer\n" } if (/^-?\d+\.?\d*\z/) { print "is a real number\n" } if (/^-?(?:\d+(?:\.\d*)?&\.\d+)\z/) { print "is a decimal number\n" } if (/^([+-]?)(?=\d&\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\z/)
{ print "a C float\n" }</lang>
There are also some commonly used modules for the task. Scalar::Util (distributed with 5.8) provides access to Perl's internal function "looks_like_number" for determining whether a variable looks like a number. Data::Types exports functions that validate data types using both the above and other regular expressions. Thirdly, there is "Regexp::Common" which has regular expressions to match various types of numbers. Those three modules are available from the CPAN.
If you're on 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?
<lang perl>sub getnum {
use POSIX; my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq ) && ($unparsed != 0) && $!) { return undef; } else { return $num; }
}
sub is_numeric { defined getnum($_[0]) }</lang>
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.
Perl 6
<lang perl6>sub is-number( $term --> Bool ) {
$term ~~ /\d/ and +$term ~~ Numeric;
} say "true" if is-number( 10111 );</lang>
PHP
<lang php><?php $string = '123'; if(is_numeric($string) && !ctype_space($string[0])) { } ?></lang>
PicoLisp
The 'format' function can be used for that. It returns NIL if the given string is not a legal number <lang PicoLisp>: (format "123") -> 123
- (format "123a45")
-> NIL
- (format "-123.45" 4)
-> 1234500</lang>
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.
<lang Pike> int(0..1) is_number(string s) {
array test = array_sscanf(s, "%s%f%s"); if (sizeof(test) == 3 && test[1] && !sizeof(test[0]) && !sizeof(test[2]) ) return true; else return false;
}
string num = "-1.234" is_number(num); -> true </lang>
PL/I
<lang PL/I> is_numeric: procedure (text) returns (bit (1));
declare text character (*); declare x float;
on conversion go to done;
get string(text) edit (x) (E(length(text),0)); return ('1'b);
done:
return ('0'b);
end is_numeric;</lang>
5 '1'B 6.7 '1'B -8.9 '1'B -4e3 '1'B 4A37 '0'B
PL/SQL
<lang plsql>FUNCTION IsNumeric( value IN VARCHAR2 ) RETURN BOOLEAN IS
help NUMBER;
BEGIN
help := to_number( value ); return( TRUE );
EXCEPTION
WHEN others THEN return( FALSE );
END;</lang>
<lang plsql>Value VARCHAR2( 10 ) := '123'; IF( IsNumeric( Value ) )
THEN NULL;
END IF;</lang>
PowerShell
Note: PowerShell 1.0 does not support 'try' THis simply tries arithmetic with the argument and if that fails, false is returned. <lang powershell>function isNumeric ($x) {
try { 0 + $x | Out-Null return $true } catch { return $false }
}</lang>
But this one doesn't work for strings like "8." though a . is appended it returns true!
Alternatively, you can use the static System.Int32.TryParse() method in the .NET framework.
<lang powershell>function isNumeric ($x) {
$x2 = 0 $isNum = [System.Int32]::TryParse($x, [ref]$x2) return $isNum
}</lang>
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. <lang PureBasic>Procedure IsNumeric(InString.s, DecimalCharacter.c = '.')
#NotNumeric = #False #IsNumeric = #True InString = Trim(InString) Protected IsDecimal, CaughtDecimal, CaughtE Protected IsSignPresent, IsSignAllowed = #True, CountNumeric Protected *CurrentChar.Character = @InString While *CurrentChar\c Select *CurrentChar\c Case '0' To '9' CountNumeric + 1 IsSignAllowed = #False Case DecimalCharacter If CaughtDecimal Or CaughtE Or CountNumeric = 0 ProcedureReturn #NotNumeric EndIf CountNumeric = 0 CaughtDecimal = #True IsDecimal = #True Case '-', '+' If IsSignPresent Or Not IsSignAllowed: ProcedureReturn #NotNumeric: EndIf IsSignPresent = #True Case 'E', 'e' If CaughtE Or CountNumeric = 0 ProcedureReturn #NotNumeric EndIf CaughtE = #True CountNumeric = 0 CaughtDecimal = #False IsSignPresent = #False IsSignAllowed = #True Default ProcedureReturn #NotNumeric EndSelect *CurrentChar + SizeOf(Character) Wend If CountNumeric = 0: ProcedureReturn #NotNumeric: EndIf ProcedureReturn #IsNumeric
EndProcedure
If OpenConsole()
PrintN("'+3183.31151E+321' = " + Str(IsNumeric("+3183.31151E+321"))) PrintN("'-123456789' = " + Str(IsNumeric("-123456789"))) PrintN("'123.45.6789+' = " + Str(IsNumeric("123.45.6789+"))) PrintN("'-e' = " + Str(IsNumeric("-e"))) Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole()
EndIf</lang> Sample output:
'+3183.31151E+321' = 1 '-123456789' = 1 '123.45.6789+' = 0 '-e' = 0
Python
<lang python>s = '123' try:
i = float(s)
except ValueError, TypeError:
# not numeric
else:
# numeric</lang>
Or for positive integers only:
<lang python>s = '123' if s.isdigit():
# numeric</lang>
Including complex, hex, binary, and octal numeric literals we get: <lang python>def is_numeric(lit):
'Return value of numeric literal string or ValueError exception'
# Handle '0' if lit == '0': return 0 # Hex/Binary litneg = lit[1:] if lit[0] == '-' else lit if litneg[0] == '0': if litneg[1] in 'xX': return int(lit,16) elif litneg[1] in 'bB': return int(lit,2) else: try: return int(lit,8) 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)))
"0" -> 0 <type 'int'> "00" -> 0 <type 'int'> "123" -> 123 <type 'int'> "-123." -> -123.0 <type 'float'> "-123e-4" -> -0.0123 <type 'float'> "0123" -> 83 <type 'int'> "0x1a1" -> 417 <type 'int'> "-123+4.5j" -> (-123+4.5j) <type 'complex'> "0b0101" -> 5 <type 'int'> "0.123" -> 0.123 <type 'float'> "-0xabc" -> -2748 <type 'int'> "-0b101" -> -5 <type 'int'>
>>></lang>
R
<lang R>> strings <- c("152", "-3.1415926", "Foo123") > suppressWarnings(!is.na(as.numeric(strings))) [1] TRUE TRUE FALSE </lang>
RapidQ
<lang RapidQ>isnumeric </lang> $Typecheck on
Defint FALSE, TRUE
FALSE = 0 TRUE = NOT FALSE
Function isNumeric(s as string, optchar as string) as integer
If len(s) = 0 then Result = FALSE Exit Function End If if instr(s,"+") > 1 then Result = FALSE exit function end if if instr(s,"-") > 1 then Result = FALSE exit function end if Defint i, ndex = 0 For i = 1 to len(s) select case asc(mid$(s,i,1)) case 43 '+ case 45 '- case 46 '. if ndex = 1 then Result = FALSE Exit function end if ndex = 1 case 48 to 57 '0 to 9 case else if instr(optchar,(mid$(s,i,1))) = 0 then Result = FALSE exit function end if end select next Result = TRUE
End Function
'============================================================ 'Begin '============================================================
showmessage (str$(isNumeric("-152.34",""))) end
REBOL
<lang REBOL> REBOL [ Title: "Is Numeric?" Author: oofoe Date: 2009-12-04 URL: http://rosettacode.org/wiki/IsNumeric ]
- Built-in.
numeric?: func [x][not error? try [to-decimal x]]
- Parse dialect for numbers.
sign: [0 1 "-"] digit: charset "0123456789" int: [some digit] float: [int "." int] number: [ sign float ["e" | "E"] sign int | sign int ["e" | "E"] sign int | sign float | sign int ]
pnumeric?: func [x][parse x number]
- Test cases.
cases: parse {
10 -99 10.43 -12.04 1e99 1.0e10 -10e3 -9.12e7 2e-4 -3.4E-5 3phase Garkenhammer e n3v3r phase3
} none foreach x cases [print [x numeric? x pnumeric? x]] </lang>
Retro
Retro does not have floating point numbers. For others, it provides isNumber?:
<lang Retro>"123" isNumber?</lang>
REXX
<lang REXX> 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 ' zzz=' + 7 ' zzz=' - 8 ' zzz=' - .9' zzz='- 19.' zzz='.7' zzz='2e3' zzz=47e567 zzz='2e-3' zzz='1.2e1' zzz=' .2E6' zzz=' 2.e5 ' zzz=' +1.2E0002 ' zzz=' +1.2e+002 ' zzz=' +0000001.200e+002 ' zzz=' - 000001.200e+002 ' zzz=' - 000008.201e-00000000000000002 '
/*Note: some REXX interpretors 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 arg.*/
/*note: some REXX interpretors don't support the ¬ (not) character.*/ </lang>
Ruby
<lang ruby>def is_numeric?(s)
begin Float(s) rescue false # not numeric else true # numeric end
end</lang>
or more compact:
<lang ruby>def is_numeric?(s)
!!Float(s) rescue false
end</lang>
Scala
<lang scala> def isNumeric(input: String): Boolean = input.forall(_.isDigit) </lang>
Scheme
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>
Smalltalk
The String class has the method isNumeric
; this method (at least on version 3.0.4) does not recognize as number strings like '-123'! So I've written an extension...
<lang smalltalk>String extend [
realIsNumeric [ (self first = $+) | (self first = $-) ifTrue: [ ^ (self allButFirst) isNumeric ] ifFalse: [ ^ self isNumeric ] ]
]
{ '1234'. "true"
'3.14'. '+3.8111'. "true" '+45'. "true" '-3.78'. "true" '-3.78.23'. "false" '123e3' "false: the notation is not recognized"
} do: [ :a | a realIsNumeric printNl ]</lang>
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.
<lang Snobol4> define('nchk(str)') :(nchk_end) nchk convert(str,'real') :s(return)f(freturn) nchk_end
- # Wrapper for testing
define('isnum(str)') :(isnum_end)
isnum isnum = 'F'; isnum = nchk(str) 'T'
isnum = isnum ': ' str :(return)
isnum_end
- # Test and display
output = isnum('123') output = isnum('123.0') output = isnum('123.') output = isnum('-123') output = isnum('3.14159') output = isnum('1.2.3') output = isnum('abc') output = isnum('A440')
end</lang>
Output:
T: 123 T: 123.0 T: 123. T: -123 T: 3.14159 F: 1.2.3 F: abc F: A440
SQL
<lang sql>declare @s varchar(10) set @s = '1234.56'
print isnumeric(@s) --prints 1 if numeric, 0 if not.
if isnumeric(@s)=1 begin print 'Numeric' end else print 'Non-numeric'</lang>
Standard ML
<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 | NONE => false
fun isReal s = case Real.scan Substring.getc (Substring.full s) of
SOME (_,subs) => Substring.isEmpty subs | NONE => false
fun isNumeric s = isInteger s orelse isReal s</lang>
Tcl
<lang tcl>if {
[string is double -strict $varname]
} then { ... }</lang>
Also string is integer (, string is alnum etc etc)
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>
VBScript
<lang vb>IsNumeric(Expr)</lang>
Returns a True if numeric and a false if not.
Vedit macro language
This routine returns TRUE if there is numeric value at current cursor location. Only signed and unsigned integers are recognized, in decimal, hex (preceded with 0x) or octal (preceded with 0o). Remove the SUPPRESS option to evaluate an expression instead of single numeric value. <lang vedit>:IS_NUMERIC: if (Num_Eval(SUPPRESS)==0 && Cur_Char != '0') {
Return(FALSE)
} else {
Return(TRUE)
}</lang>
Visual Basic .NET
<lang vbnet>Dim Value As String = "+123"
If IsNumeric(Value) Then
PRINT "It is numeric."
End If</lang>
- Programming Tasks
- Text processing
- ActionScript
- Ada
- ALGOL 68
- APL
- AutoHotkey
- AWK
- BASIC
- BBC BASIC
- Bracmat
- C
- C++
- C sharp
- Clojure
- CoffeeScript
- ColdFusion
- Common Lisp
- D
- Delphi
- E
- Erlang
- Euphoria
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- LabVIEW
- Lasso
- Liberty BASIC
- Lisaac
- Logo
- Lua
- Mathematica
- MATLAB
- MATLAB examples needing attention
- Examples needing attention
- MAXScript
- Mirah
- MIRC Scripting Language
- Modula-3
- MUMPS
- Nemerle
- Objective-C
- OCaml
- Octave
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PL/SQL
- PowerShell
- PureBasic
- Python
- R
- RapidQ
- REBOL
- Retro
- REXX
- Ruby
- Scala
- Scheme
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Tcl
- Toka
- VBScript
- Vedit macro language
- Visual Basic .NET
- GUISS/Omit
- String manipulation