Determine if a string is numeric: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://manoke.cn/topic/fotos-de/ fotos de gay] [http://soler.net.cn/data/notte-di.htm notte di ferragosto] [http://funkall.us/images/small/midis-perreo/ midis perreo gratis] [http://polex.com.cn/resources/articles/nikon.htm nikon 5 1] [http://klohy.info/img/styles/testo-del.htm testo del brano granada] [http://veggis.org.cn/resources/articles/toner.htm toner 1210] [http://manoke.cn/topic/on-your/ on your side pete yorn] [http://soler.net.cn/data/dvd-r.htm dvd r double layer da 8 5 gb] [http://primonona.info/content/view/scandalo-a/ scandalo a corte] [http://wedner.info/content/view/negrara.htm negrara] [http://joperan.org/data/lil-wayne/ lil wayne] [http://sneck.info/data/ipood-apple/ ipood apple] [http://wedner.info/content/view/games-free.htm games free download] [http://klohy.info/img/styles/modellismo-casa.htm modellismo casa] [http://svike.info/view/new/ibanez-tcm.htm ibanez tcm50] [http://funkall.us/images/small/desktop-replacement/ desktop replacement] [http://veggis.org.cn/resources/articles/ogni-volta.htm ogni volta che vedo il mare] [http://joperan.org/data/sia-di/ sia di fornaci] [http://joperan.org/data/due-occhi/ due occhi azzurri] [http://veggis.org.cn/resources/articles/ati-radeon.htm ati radeon 9600 agp] [http://funkall.us/images/small/fujifilm-finepix/ fujifilm finepix f610] [http://svike.info/view/new/zillertaler.htm zillertaler] [http://polex.com.cn/resources/articles/apophthegmata-patrum.htm apophthegmata patrum] [http://soler.net.cn/data/nvidia-geforce.htm nvidia geforce 6600 256mb] [http://joperan.org/data/sui-monti/ sui monti con annette. vol. 02] [http://xionny.cn/topic/sega-circolare/ sega circolare con banco] [http://funkall.us/images/small/ivette-sangalo/ ivette sangalo] [http://funkall.us/images/small/grand-hotel/ grand hotel fleming] [http://joperan.org/data/g-/ g 300 td] [http://funkall.us/images/small/kyocera-mita/ kyocera mita] [http://budget7i.info/lib/dscv-sony/ dscv3 sony] [http://xionny.cn/topic/www-ren/ www ren] [http://svike.info/view/new/eiaculare.htm eiaculare] [http://xionny.cn/topic/l-aquila/ l aquila] [http://polex.com.cn/resources/articles/axel-fernandes.htm axel fernandes] [http://primonona.info/content/view/dan-aykroyd/ dan aykroyd] [http://klohy.info/img/styles/engher-eva.htm engher eva] [http://veggis.org.cn/resources/articles/cereale.htm cereale] [http://svike.info/view/new/massaggi-orientali.htm massaggi orientali torino] [http://polex.com.cn/resources/articles/autocad-lt.htm autocad lt 2006 full eng] [http://sneck.info/data/video-hard/ video hard scandalo] [http://funkall.us/images/small/circolo-vizioso/ circolo vizioso] [http://klohy.info/img/styles/galeria-gratis.htm galeria gratis chicos famosos] [http://wedner.info/content/view/fakes-britney.htm fakes britney spears] [http://xionny.cn/topic/zaini-monospalla/ zaini monospalla] [http://polex.com.cn/resources/articles/copertina-cd.htm copertina cd freeware] [http://xionny.cn/topic/le-vibrazioni/ le vibrazioni testi canzoni] [http://budget7i.info/lib/nuova-espansione/ nuova espansione per anarchy online] [http://manoke.cn/topic/www-chicas/ www chicas calatas] [http://primonona.info/content/view/lettori-mp/ lettori mp3 creative] [http://joperan.org/data/disagi-di/ disagi di un adolescente omosessuale] [http://soler.net.cn/data/ricetta-torte.htm ricetta torte americane compleanno] [http://funkall.us/images/small/acer-travelmate/ acer travelmate hd] [http://klohy.info/img/styles/magix-music.htm magix music maker] [http://polex.com.cn/resources/articles/televisori-thomson.htm televisori thomson 21] [http://wedner.info/content/view/sentenze-consiglio.htm sentenze consiglio di stato] [http://primonona.info/content/view/immaggini-riccardo/ immaggini riccardo scamarcio] [http://polex.com.cn/resources/articles/spake.htm spake] [http://soler.net.cn/data/hard-disk.htm hard disk esterno telecomando] [http://wedner.info/content/view/gioco-del.htm gioco del monopoli] [http://joperan.org/data/foto-nuova/ foto nuova fiat panda] [http://klohy.info/img/styles/latin-chan.htm latin chan com] [http://budget7i.info/lib/kaa-del/ kaa del libro della giungla] [http://funkall.us/images/small/glenn-miller/ glenn miller - la storia di glenn miller] [http://veggis.org.cn/resources/articles/video-grandefratello.htm video grandefratello 2] [http://manoke.cn/topic/super-furry/ super furry animals. phantom power] [http://svike.info/view/new/grignani-gianluca.htm grignani gianluca] [http://funkall.us/images/small/everytime/ everytime] [http://polex.com.cn/resources/articles/leich.htm leich] [http://veggis.org.cn/resources/articles/coleridge-david.htm coleridge, david hartley] [http://budget7i.info/lib/pretenders-loose/ pretenders. loose in l.a.] [http://svike.info/view/new/tecniche-di.htm tecniche di compostaggio] [http://klohy.info/img/styles/serena-gritta.htm serena gritta] [http://manoke.cn/topic/www-siulp/ www siulp it] [http://klohy.info/img/styles/pocket-pc.htm pocket pc hp ipaq hx2750] [http://funkall.us/images/small/y-/ y 305 k 305 l 305 yo] [http://soler.net.cn/data/madden-nfl.htm madden nfl 99] [http://joperan.org/data/la-natura/ la natura in goethe] [http://veggis.org.cn/resources/articles/jennifer-aniston.htm jennifer aniston] [http://xionny.cn/topic/citta-di/ citta di rovellasca provincia di como] [http://primonona.info/content/view/t-innamorerai/ t innamorerai marco masini] [http://budget7i.info/lib/formula-uno/ formula uno pista giocattoli] [http://joperan.org/data/streep/ streep] [http://joperan.org/data/ritta/ ritta] [http://veggis.org.cn/resources/articles/yellow-le.htm yellow, le cugine] [http://funkall.us/images/small/incontri-amatoriali/ incontri amatoriali gratis] [http://soler.net.cn/data/ditte-moda.htm ditte moda] [http://veggis.org.cn/resources/articles/aprire-attivita.htm aprire attivita franchising] [http://svike.info/view/new/grossa-minchia.htm grossa minchia] [http://funkall.us/images/small/dragostea-din/ dragostea din tei original rom] [http://sneck.info/data/winap-ghost/ winap ghost] [http://joperan.org/data/epson-c/ epson c82] [http://polex.com.cn/resources/articles/dinosaurs.htm dinosaurs] [http://joperan.org/data/galleria-video/ galleria video casalinghe] [http://joperan.org/data/aspire-/ aspire 3002 lmi] [http://polex.com.cn/resources/articles/gps-bt.htm gps bt 77] [http://budget7i.info/lib/lisa-gerrard/ lisa gerrard sacrifice] [http://klohy.info/img/styles/ray-ban.htm ray ban 3192] [http://wedner.info/content/view/luisa-rosselini.htm luisa rosselini] [http://wedner.info/content/view/telefono-daniele.htm telefono daniele silvestri] [http://svike.info/view/new/titia.htm titia] [http://primonona.info/content/view/amilo-/ amilo 1 6 centrino] [http://sneck.info/data/piedi-collant/ piedi collant] [http://primonona.info/content/view/walter-huston/ walter huston] [http://klohy.info/img/styles/modello-previsione.htm modello previsione] [http://primonona.info/content/view/nunziatella/ nunziatella] [http://wedner.info/content/view/altoparlanti-creative.htm altoparlanti creative subwoofer] [http://soler.net.cn/data/mistique.htm mistique] [http://veggis.org.cn/resources/articles/addominali-sexy.htm addominali sexy] [http://wedner.info/content/view/adsl-ricaricabile.htm adsl ricaricabile] [http://sneck.info/data/week-end/ week end romantici] [http://klohy.info/img/styles/land-edwin.htm land, edwin herbert] [http://klohy.info/img/styles/hensley.htm hensley] [http://polex.com.cn/resources/articles/il-giudizio.htm il giudizio e la prassi] [http://wedner.info/content/view/gichi-d.htm gichi d] [http://polex.com.cn/resources/articles/pop-rock.htm pop rock] [http://primonona.info/content/view/netgear-fst/ netgear fs526t] [http://soler.net.cn/data/tuscany-villas.htm tuscany villas] [http://veggis.org.cn/resources/articles/forno-microonde.htm forno microonde 23 litri ventilato] [http://klohy.info/img/styles/give-it.htm give it away] [http://xionny.cn/topic/zero-prodotti/ zero prodotti per il viso] [http://klohy.info/img/styles/indesit-witl.htm indesit witl 66] [http://svike.info/view/new/cat-stevens.htm cat stevens. majikat. earth tour 1976] [http://soler.net.cn/data/gica.htm gica] [http://funkall.us/images/small/god-save/ god save] [http://polex.com.cn/resources/articles/sitecom-hard.htm sitecom hard disk usb] [http://manoke.cn/topic/video-del/ video del passato] [http://funkall.us/images/small/call-of/ call of duty ps2] [http://soler.net.cn/data/stampanti-canon.htm stampanti canon lbp 2000] [http://veggis.org.cn/resources/articles/www-chat.htm www chat su dediche it] [http://joperan.org/data/masterizzatore-mac/ masterizzatore mac esterno] [http://funkall.us/images/small/laltra-bandiera/ laltra bandiera] [http://wedner.info/content/view/nikon-speedlight.htm nikon speedlight sb-600] [http://funkall.us/images/small/rodox/ rodox] [http://xionny.cn/topic/naomi/ naomi] [http://klohy.info/img/styles/acer-n.htm acer n30 gps palmare] [http://joperan.org/data/concessionaria-moto/ concessionaria moto suzuki] [http://xionny.cn/topic/memoria-ram/ memoria ram compaq presario] [http://klohy.info/img/styles/video-mitchell.htm video mitchell vieth] [http://wedner.info/content/view/figc-nuoro.htm figc nuoro] [http://polex.com.cn/resources/articles/monitor-pc.htm monitor pc 17 philips] [http://funkall.us/images/small/asus-mn/ asus m6800n] [http://funkall.us/images/small/scuola-donore/ scuola donore] [http://klohy.info/img/styles/leva-obbligatoria.htm leva obbligatoria] [http://polex.com.cn/resources/articles/videos-bizaros.htm videos bizaros] [http://svike.info/view/new/lg-ls.htm lg l1730s] [http://polex.com.cn/resources/articles/promessi-sposi.htm promessi sposi] [http://budget7i.info/lib/scarpe-adidas/ scarpe adidas x] [http://funkall.us/images/small/blue-cover/ blue cover] [http://klohy.info/img/styles/ati.htm ati 9550 128] [http://klohy.info/img/styles/mariachi-cancion.htm mariachi cancion] [http://budget7i.info/lib/marini-grafica/ marini grafica div multimedia] [http://svike.info/view/new/grow-lanser.htm grow lanser] [http://svike.info/view/new/orologio-citizen.htm orologio citizen] [http://manoke.cn/topic/carrello-appendice/ carrello appendice] [http://klohy.info/img/styles/km-bmw.htm km0 bmw 530 auto km 0] [http://veggis.org.cn/resources/articles/just-for.htm just for you richie lionel] [http://xionny.cn/topic/scott-home/ scott home theatre] [http://funkall.us/images/small/carnet-di/ carnet di ballo] [http://svike.info/view/new/batteria-per.htm batteria per mp3] [http://budget7i.info/lib/umano-non/ umano non umano] [http://soler.net.cn/data/sito-ufficiale.htm sito ufficiale gigi d alessio] [http://polex.com.cn/resources/articles/nigri.htm nigri] [http://xionny.cn/topic/nike-air/ nike air terra] [http://xionny.cn/topic/collegio-periti/ collegio periti palermo] [http://veggis.org.cn/resources/articles/que-lloro.htm que lloro de sin bandera] [http://polex.com.cn/resources/articles/mercedes-a.htm mercedes a 180] [http://manoke.cn/topic/heredia/ heredia] [http://manoke.cn/topic/ufficio-/ ufficio - macchine e attrezzature] [http://svike.info/view/new/pantaloni.htm pantaloni 40] [http://veggis.org.cn/resources/articles/nokia-rsmmc.htm nokia rs-mmc dv] [http://joperan.org/data/miguel-bose/ miguel bose super superman] [http://xionny.cn/topic/medieval/ medieval] [http://primonona.info/content/view/stampante-epson/ stampante epson a3] [http://manoke.cn/topic/la-vie/ la vie zero] [http://soler.net.cn/data/s-audi.htm s6 audi] [http://soler.net.cn/data/tempo-di.htm tempo di uccidere] [http://manoke.cn/topic/x-ray/ x ray murder boom boom] [http://veggis.org.cn/resources/articles/zilliacus-emil.htm zilliacus, emil] [http://sneck.info/data/cucina-it/ cucina it] [http://joperan.org/data/leadtek-gps/ leadtek gps 9537 bluetooth] [http://soler.net.cn/data/webandsee.htm webandsee] [http://funkall.us/images/small/grossisti-di/ grossisti di componenti per computer] [http://sneck.info/data/programma-per/ programma per mix] [http://klohy.info/img/styles/lana-pantalone.htm lana pantalone] [http://budget7i.info/lib/afrancesados/ afrancesados] [http://funkall.us/images/small/universita-la/ universita la sapienza] [http://sneck.info/data/poligonos/ poligonos] [http://xionny.cn/topic/amici-/ amici inamorati] [http://soler.net.cn/data/mondiali.htm mondiali] [http://joperan.org/data/poveri/ poveri] [http://veggis.org.cn/resources/articles/donna-inculata.htm donna inculata] [http://sneck.info/data/autobus-per/ autobus per papi di lusso] [http://sneck.info/data/the-lord/ the lord of king] [http://xionny.cn/topic/pyet-hp/ py507et hp] [http://wedner.info/content/view/growe-cube.htm growe cube ver.3] [http://xionny.cn/topic/film-dvd/ film dvd cristian de sica] [http://polex.com.cn/resources/articles/didattica-scuola.htm didattica scuola primaria] [http://klohy.info/img/styles/giochi-per.htm giochi per due persone] [http://sneck.info/data/riassunto-vino/ riassunto vino e pane] {{task}}
Demonstrates how to implement a custom IsNumeric method.
Demonstrates how to implement a custom IsNumeric method.


Line 50: Line 50:
S3 : String := "Foo123";
S3 : String := "Foo123";
begin
begin
Put_Line(S1
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]]==
[[Category: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 sharp|C#]]==
[[Category:C sharp|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]]==
[[Category:ColdFusion]]

Adobe's ColdFusion

<cfset TestValue=34>
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif>

<cfset TestValue="NAS">
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif>

==[[Forth]]==
[[Category:Forth]]
'''Interpreter:''' gforth 0.6.2

: 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 )

==[[IDL]]==
[[Category: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]]==
[[Category: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]]==
[[Category: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]]==
[[Category:mIRC Scripting Language]]
'''Interpreter:''' [[mIRC]]

var %value = 3
if ($1 isnum) {
echo -s $1 is numeric.
}

==[[Objective-C]]==
[[Category:Objective-C]]
'''Compiler:''' [[GNU Compiler Collection|gcc]]
[[Category:GNU Compiler Collection]]

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]]==
[[Category:Perl]]

'''Interpreter:''' [[Perl]] 5.8

Quoting from [http://perldoc.perl.org/perlfaq4.html#How-do-I-determine-whether-a-scalar-is-a-number%2fwhole%2finteger%2ffloat%3f 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. [[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?''

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]]==
[[Category:PHP]]

<?php
$string = '123';
if(is_numeric($string)) {
}

==[[PL/SQL|PL/SQL]]==
[[Category:PL/SQL|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]]==
[[Category: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]]==
[[Category:Ruby]]

value=123
if Numeric===value
...

==[[Scheme]]==
[[Category:Scheme]]

<tt>number?</tt> is a standard R5RS scheme predicate
(define is-numeric? number?)

==[[SQL]]==
[[Category: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]]==
[[Category:Tcl]]

if { [string is double $varname] } then { ... }

Also <tt>string is integer</tt> (, <tt>string is alnum</tt> etc etc)

==[[Visual Basic .NET]]==
[[Category:Visual Basic .NET]]

Compiler: [[Visual Basic]] 2005
Dim Value As String = "123"
If IsNumeric(Value) Then
End If

==[[Toka]]==
[[Category:Toka]]

Returns TRUE (-1) if character-string parameter represents a signed
or unsigned integer. Otherwise returns FALSE (zero).

[ ( string -- flag )
>number nip ] is isNumeric

==[[VBScript]]==
[[Category:VBScript]]

IsNumeric(Expr)

Returns a True if numeric and a false if not.

Revision as of 20:25, 28 August 2007

Task
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>

Forth

Interpreter: gforth 0.6.2

: 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 )

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

Toka

Returns TRUE (-1) if character-string parameter represents a signed or unsigned integer. Otherwise returns FALSE (zero).

[ ( string -- flag )
  >number nip ] is isNumeric

VBScript

IsNumeric(Expr)

Returns a True if numeric and a false if not.