Determine if a string is numeric
You are encouraged to solve this task according to the task description, using any language you may know.
Demonstrates how to implement a custom IsNumeric method.
Ada
The first file is the package interface containing the declaration of the Is_Numeric function.
package Numeric_Tests is 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.
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;
The last file shows how the Is_Numeric function can be called.
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;
The output of the program above is:
152 results in TRUE -3.1415926 results in TRUE Foo123 results in FALSE
C
Returns true (non-zero) if character-string parameter represents a signed or unsigned integer. Otherwise returns false (zero).
#include <stdlib.h> int isNumeric (const char * s) { char * p; strtol (s, &p, 10); return !*p; }
C#
Framework: .NET 2.0+
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 }
Framework: .NET 1.0+
using System.Text.RegularExpressions; public static bool IsNumeric(string s) { try { Double.Parse(s); return true; } catch { return false; } }
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>
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
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.
public boolean isNumeric(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { // s is not numeric return false; } }
Alternative 1 : Check that each character in the string is number. Note that this will only works for integers.
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 }
Alternative 2 : use a regular expression (a more elegant solution). Also, only for integers.
public static boolean IsNumeric(string inputData) { final static Regex isNumber = new Regex(@"^-{0,1}\d+$"); Match m = isNumber.Match(inputData); return m.Success; }
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')}
mIRC Scripting Language
Interpreter: mIRC
var %value = 3 if ($1 isnum) { echo -s $1 is numeric. }
Objective-C
Compiler: gcc
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.
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
Perl
Interpreter: Perl 5.8
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.
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" }
There are also some commonly used modules for the task. 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 "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?
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]) }
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
<?php $string = '123'; if(is_numeric($string)) { }
PL/SQL
FUNCTION IsNumeric( value IN VARCHAR2 ) RETURN BOOLEAN IS help NUMBER; BEGIN help := to_number( value ); return( TRUE ); EXCEPTION WHEN others THEN return( FALSE ); END;
Value VARCHAR2( 10 ) := '123'; IF( IsNumeric( Value ) ) THEN NULL; END IF;
Python
s = '123' try: i = int(s) # use i except ValueError: # s is not numeric
Or for positive integers:
s = '123' if s.isdigit(): ...
Ruby
value=123 if Numeric===value ...
Scheme
number? is a standard R5RS scheme predicate
(define is-numeric? number?)
SQL
-- Tested on Microsoft SQL Server 2005 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'
Tcl
if { string is double $varname } then { ... }
Also string is integer (, string is alnum etc etc)
Visual Basic .NET
Compiler: Visual Basic 2005
Dim Value As String = "123" If IsNumeric(Value) Then End If
VBScript
IsNumeric(Expr)
Returns a True if numeric and a false if not.