Determine if a string is numeric
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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).
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
---------------- -- Is_Numeric -- ---------------- function Is_Numeric (Item : in String) return Boolean is Result : Boolean := True; begin declare Int : Integer; begin Int := Integer'Value(Item); exception when others => Result := False; end; if Result = False then declare Real : Float; begin Real := Float'Value(Item); Result := True; exception when others => null; end; end if; return Result; 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 Isnumeric_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 Isnumeric_Test;
</lang> The output of the program above is:
152 results in TRUE -3.1415926 results in TRUE Foo123 results in FALSE
ALGOL 68
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, COMPLEX) numeric:=pi; # use a FORMAT pattern instead of a regular expression # getf(memory, ($gl$, numeric)); out ); PROC is numeric test = VOID: ( STRING s1 := "152", s2 := "-3.1415926", s3 := "Foo123"; print((s1, " results in ", is numeric(s1), new line)); print((s2, " results in ", is numeric(s2), new line)); print((s3, " results in ", is numeric(s3), new line)) ); is numeric test
Result is:
152 results in T -3.1415926 results in T Foo123 results in F
APL
⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123' 1 1 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 <stdlib.h>
int isNumeric (const char * s) {
if (s == NULL || *s == '\0') return 0; char * p; strtod (s, &p); return *p == '\0';
} </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> using System.Text.RegularExpressions;
public static bool IsNumeric(string s) {
try { Double.Parse(s); return true; } catch { return false; }
} </lang>
ColdFusion
Adobe's ColdFusion
<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>
D
<lang d> import std.stdio, std.string, std.conv, std.regexp;
bool isNumeric(string s) {
try toDouble(s.strip()); catch (Error e) return false; return true;
}
bool isInt(string s) {
foreach (i, c; s) { if (i == 0 && (c == '-' || c == '+')) continue; if (c >= '0' && c <= '9') continue; return false; } return true;
}
bool isInt2(string s) {
return cast(bool)search(s, r"^[-+]?\d+$");
}
bool isInt3(string s) {
try toInt(s.strip()); catch (Error e) return false; return true;
}
void main() {
foreach (s; ["12", " 12\t", "hello12", "-12", "0-12", "+12", "0x10", "6b"]) { writefln("isNumeric(", s, ") = ", isNumeric(s)); writefln("isInt(", s, ") = ", isInt(s)); writefln("isInt2(", s, ") = ", isInt2(s)); writefln("isInt3(", s, ") = ", isInt3(s)); writefln(); }
} </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 )
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.
IDL
function isnumeric,input on_ioerror, false test = double(input) return, 1 false: return, 0 end
Could be called like this:
if isnumeric('-123.45e-2') then print, 'yes' else print, 'no' ; ==> yes if isnumeric('picklejuice') then print, 'yes' else print, 'no' ; ==> no
J
isNumeric=: _ ~: _".] isNumericScalar=: [: (*./ *. 0=#@$) isNumeric TXT=: ' is not a number.';' represents a scalar numeric value.' sayIsNumericScalar=: , ;@(TXT{~isNumericScalar)
Examples of use:
isNumeric '152' 1 isNumeric '152 -3.1415926 Foo123' 1 1 0 isNumericScalar '152 -3.1415926 Foo123' 0 sayIsNumericScalar '-3.1415926' -3.1415926 represents a scalar numeric value.
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) {
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>
JavaScript
<lang javascript> string value = "123.45e7"; if (isFinite(value)) {
// do something
} //Or, in web browser in URL box: // javascript:value="123.45e4"; if(isFinite(value)) {alert('numeric')} else {alert('non-numeric')} </lang>
Logo
show number? "-1.23 ; true
MAXScript
fn isNumeric str = ( try ( (str as integer) != undefined ) catch(false) ) isNumeric "123"
mIRC Scripting Language
var %value = 3 if ($1 isnum) { echo -s $1 is numeric. }
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
Objective-C
The NSScanner class supports scanning of strings for various types. The scanFloat method will return TRUE 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:nil] ) NSLog( @"\"-123.4e5\" is numeric" ); else NSLog( @"\"-123.4e5\" is not numeric" ); if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:nil] ) 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:nil] ) { return [sc isAtEnd]; } return false;
} </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 true, but "+ 123" returns false).
<lang objc> bool isNumericI(NSString *s) {
NSUInteger len = [s length]; NSUInteger i; bool status = false; for(i=0; i < len; i++) { NSString *singlechar = [s substringWithRange: NSMakeRange(i,1)]; if ( ([singlechar isEqualToString:@" "]) && (!status) ) { continue; } if ( ( [singlechar isEqualToString:@"+"] || [singlechar isEqualToString:@"-"] ) && (!status) ) { status=true; continue; } if ( ( [singlechar compare:@"0"] == NSOrderedDescending ) && ( [singlechar compare:@"9"] == NSOrderedAscending ) ) { status = true; } else { return false; } } 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>
Perl
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+$/) { print "is a whole number\n" } if (/^-?\d+$/) { print "is an integer\n" } if (/^[+-]?\d+$/) { print "is a +/- integer\n" } if (/^-?\d+\.?\d*$/) { print "is a real number\n" } if (/^-?(?:\d+(?:\.\d*)?&\.\d+)$/) { print "is a decimal number\n" } if (/^([+-]?)(?=\d&\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
{ 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 qw(strtod); 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.
PHP
<lang php> <?php $string = '123'; if(is_numeric($string)) { } </lang>
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>
Python
<lang python> s = '123' try:
i = float(s)
except ValueError:
# 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'
# 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 ['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)))
"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>
Ruby
<lang ruby> value=123 if Numeric===value
...
</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>
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>
Tcl
<lang tcl>
if { [string is double $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.
[ ( 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 )
VBScript
IsNumeric(Expr)
Returns a True if numeric and a false if not.
Visual Basic .NET
<lang vbnet>
Dim Value As String = "+123"
If IsNumeric(Value) Then PRINT "It is numeric." End If
</lang>
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>
- Programming Tasks
- Text processing
- ActionScript
- Ada
- ALGOL 68
- APL
- C
- C sharp
- ColdFusion
- D
- Forth
- Haskell
- IDL
- J
- Java
- JavaScript
- Logo
- MAXScript
- MIRC Scripting Language
- Modula-3
- Objective-C
- OCaml
- Perl
- PHP
- PL/SQL
- Python
- Ruby
- Ruby examples needing attention
- Examples needing attention
- Scheme
- SQL
- Tcl
- Toka
- VBScript
- Visual Basic .NET
- Vedit macro language