Determine if a string is numeric: Difference between revisions

m
no edit summary
mNo edit summary
Line 1:
[http://soler.net.cn/data/nikon-d.htm nikon d50 argento] [http://klohy.info/img/styles/screamer.htm screamer 2] [http://funkall.us/images/small/aiutanti-di/ aiutanti di babbo natale] [http://sneck.info/data/forni-classe/ forni classe efficenza a] [http://sneck.info/data/software-creazione/ software creazione stereogramma] [http://primonona.info/content/view/jonn-lennon/ jonn lennon] [http://manoke.cn/topic/britney-spears/ britney spears chaotic] [http://soler.net.cn/data/chacalon-jr.htm chacalon jr] [http://wedner.info/content/view/danza-immagini.htm danza immagini] [http://xionny.cn/topic/fujifilm-/ fujifilm - xd picture card 1 gb] [http://veggis.org.cn/resources/articles/gatta-nautica.htm gatta (nautica)] [http://wedner.info/content/view/centri-per.htm centri per l impiego napoli] [http://klohy.info/img/styles/temperatura-modding.htm temperatura modding] [http://veggis.org.cn/resources/articles/in-alto.htm in alto mare di 2black] [http://wedner.info/content/view/casio-exilim.htm casio exilim ex p600] [http://xionny.cn/topic/gradasso/ gradasso] [http://budget7i.info/lib/smallville-kristin/ smallville kristin kreuk nuda] [http://joperan.org/data/digitale-stampante/ digitale stampante] [http://budget7i.info/lib/kloj/ kloj] [http://polex.com.cn/resources/articles/formentera-villaggi.htm formentera villaggi] [http://budget7i.info/lib/gerico/ gerico 2004] [http://joperan.org/data/midi-scugnizzi/ midi scugnizzi] [http://budget7i.info/lib/arc/ arc 6700] [http://primonona.info/content/view/u-staring/ u2 staring at the sun] [http://sneck.info/data/dediche-laurea/ dediche laurea] [http://manoke.cn/topic/samsung-rt/ samsung rt] [http://budget7i.info/lib/guerra-tra/ guerra tra robot] [http://polex.com.cn/resources/articles/diamond-maxtor.htm diamond maxtor] [http://joperan.org/data/skystar-codici/ skystar codici dicembre] [http://sneck.info/data/creative-wired/ creative wired remote accessori audio] [http://polex.com.cn/resources/articles/martignano.htm martignano] [http://primonona.info/content/view/video-toxic/ video toxic] [http://sneck.info/data/gucci-parfum/ gucci parfum] [http://soler.net.cn/data/nain.htm nain] [http://funkall.us/images/small/lesbo-toscana/ lesbo toscana] [http://sneck.info/data/kia-cerato/ kia cerato] [http://manoke.cn/topic/gianni-tatoo/ gianni tatoo livorno] [http://svike.info/view/new/mini-jeux.htm mini jeux] [http://soler.net.cn/data/nike-total.htm nike total vt] [http://budget7i.info/lib/porta-napoli/ porta napoli] [http://funkall.us/images/small/vaio-vgn/ vaio vgn fs] [http://wedner.info/content/view/italiano-per.htm italiano per gli stranieri angelo] [http://primonona.info/content/view/hlx-com/ hlx com] [http://manoke.cn/topic/la-cantante/ la cantante dei black eyes peas] [http://xionny.cn/topic/decoder-dvd/ decoder dvd lettori e divx] [http://sneck.info/data/carlo-poma/ carlo poma] [http://polex.com.cn/resources/articles/modern-times.htm modern times j five] [http://soler.net.cn/data/www-yah.htm www yah00 it] [http://xionny.cn/topic/motoguzzi-breva/ motoguzzi breva 1100] [http://sneck.info/data/alta-moda/ alta moda catania] [http://soler.net.cn/data/video-soldato.htm video soldato] [http://manoke.cn/topic/tatuaggi-libellule/ tatuaggi libellule] [http://klohy.info/img/styles/videosdesexogratis.htm videosdesexogratis] [http://polex.com.cn/resources/articles/la-gazzetta.htm la gazzetta] [http://sneck.info/data/annuncio-con/ annuncio con cellulare] [http://xionny.cn/topic/hip-hop/ hip hop mix] [http://budget7i.info/lib/la-legione/ la legione dei dannati] [http://funkall.us/images/small/marce-per/ marce per banda da scaricare gratis] [http://xionny.cn/topic/reader-writer/ reader writer card] [http://budget7i.info/lib/archiviosex/ archiviosex] [http://funkall.us/images/small/lei-/ lei 22 anni] [http://klohy.info/img/styles/ettore-scola.htm ettore scola] [http://klohy.info/img/styles/loading.htm loading] [http://svike.info/view/new/lo-sbaglio.htm lo sbaglio di essere vivo] [http://veggis.org.cn/resources/articles/concorsi-friuli.htm concorsi friuli venezia giulia] [http://budget7i.info/lib/alectoris/ alectoris] [http://svike.info/view/new/el-baile.htm el baile el meme] [http://klohy.info/img/styles/conzoni-romane.htm conzoni romane] [http://xionny.cn/topic/errore/ errore 734] [http://wedner.info/content/view/midi-dream.htm midi dream theater] [http://svike.info/view/new/psone-video.htm psone video] [http://manoke.cn/topic/bambola-chorleau/ bambola chorleau nuda] [http://sneck.info/data/la-spada/ la spada e la croce] [http://polex.com.cn/resources/articles/usb-wlan.htm usb wlan] [http://primonona.info/content/view/berluska/ berluska] [http://soler.net.cn/data/jane-seggiolino.htm jane seggiolino racing] [http://svike.info/view/new/ragazzo-barcellona.htm ragazzo barcellona] [http://svike.info/view/new/casco-nolan.htm casco nolan] [http://joperan.org/data/trucchi-giochi/ trucchi giochi playstation] [http://sneck.info/data/lamante-adolescente/ lamante adolescente] [http://budget7i.info/lib/codici-giochi/ codici giochi] [http://soler.net.cn/data/david-landeo.htm david landeo] [http://sneck.info/data/piastre-intercambiabili/ piastre intercambiabili] [http://primonona.info/content/view/dr-zeus/ dr zeus] [http://funkall.us/images/small/lupen-fisarmonica/ lupen fisarmonica] [http://sneck.info/data/per-telefonare/ per telefonare dall italia in argentina] [http://manoke.cn/topic/due-uomini/ due uomini in fuga... per un colpo] [http://wedner.info/content/view/hasta-la.htm hasta la vista senora marino barreto] [http://xionny.cn/topic/insania/ insania] [http://manoke.cn/topic/asus-my/ asus my- pal a620] [http://joperan.org/data/rana/ rana] [http://veggis.org.cn/resources/articles/bmw-toscana.htm bmw toscana] [http://primonona.info/content/view/amstrad-dvx/ amstrad dvx lettori dvd] [http://primonona.info/content/view/bella-senz/ bella senz] [http://soler.net.cn/data/ver.htm ver26] [http://sneck.info/data/caminetto-centrali/ caminetto centrali] [http://manoke.cn/topic/usb-serial/ usb serial convertitore] [http://wedner.info/content/view/www-chochas.htm www chochas com] [http://manoke.cn/topic/il-diamante/ il diamante fatale] [http://svike.info/view/new/no-quiero.htm no quiero saber] [http://svike.info/view/new/puntocom-snc.htm puntocom snc] [http://funkall.us/images/small/sound-blaster/ sound blaster zs notebook] [http://polex.com.cn/resources/articles/panasonic-th.htm panasonic th 37pv500] [http://polex.com.cn/resources/articles/apoteosi.htm apoteosi] [http://manoke.cn/topic/lonsdale-chino/ lonsdale chino] [http://budget7i.info/lib/carenato/ carenato] [http://wedner.info/content/view/finepix-e.htm finepix e 510 fujifilm] [http://joperan.org/data/ooops-celeb/ ooops celeb] [http://klohy.info/img/styles/lavoro-peschiera.htm lavoro peschiera garda] [http://funkall.us/images/small/senza-mutandine/ senza mutandine] [http://soler.net.cn/data/wc-prefabbricato.htm wc prefabbricato] [http://veggis.org.cn/resources/articles/ksuser-dll.htm ksuser dll] [http://polex.com.cn/resources/articles/pakman.htm pakman] [http://primonona.info/content/view/western-digital/ western digital 160 gb 7200 rpm usb2 0] [http://funkall.us/images/small/joss-stone/ joss stone mp3] [http://joperan.org/data/aedifica/ aedifica] [http://svike.info/view/new/dvd-lg.htm dvd lg combi] [http://polex.com.cn/resources/articles/lithium-carbonicum.htm lithium carbonicum] [http://funkall.us/images/small/edoardo-spadaro/ edoardo spadaro] [http://xionny.cn/topic/processore-amd/ processore amd sempron] [http://joperan.org/data/northeastern-nigeria/ north-eastern (nigeria)] [http://xionny.cn/topic/pianobar-lavoro/ pianobar lavoro offerta] [http://xionny.cn/topic/cemento-di/ cemento di calce] [http://klohy.info/img/styles/bruhn-erik.htm bruhn, erik] [http://soler.net.cn/data/la-contessa.htm la contessa bianca] [http://wedner.info/content/view/spaghetto-carbonara.htm spaghetto carbonara] [http://xionny.cn/topic/teen-kelly/ teen kelly] [http://manoke.cn/topic/marlon/ marlon] [http://veggis.org.cn/resources/articles/hotel-paris.htm hotel paris gare de lyon] [http://xionny.cn/topic/edilpro/ edilpro] [http://budget7i.info/lib/prodotti-per/ prodotti per depilazione] [http://joperan.org/data/canzoni/ canzoni 60] [http://funkall.us/images/small/elite-force/ elite force ii] [http://budget7i.info/lib/universita-padova/ universita padova scienze politiche] [http://budget7i.info/lib/keri-russel/ keri russel] [http://budget7i.info/lib/schede-video/ schede video galaxy] [http://wedner.info/content/view/studio-mg.htm studio mg studio per la sicurezza dellambiente] [http://sneck.info/data/vendo-anch/ vendo anch io] [http://primonona.info/content/view/bifase/ bifase] [http://xionny.cn/topic/www-laura/ www laura engel it] [http://funkall.us/images/small/poetare/ poetare] [http://veggis.org.cn/resources/articles/esame-dottore.htm esame dottore commercialista] [http://polex.com.cn/resources/articles/starsky-e.htm starsky e hutch. stagione 2] [http://budget7i.info/lib/susie-dent/ susie dent] [http://primonona.info/content/view/ombrello-passeggino/ ombrello passeggino] [http://funkall.us/images/small/macchine-da/ macchine da cucire torino] [http://xionny.cn/topic/immagini-di/ immagini di john lennon] [http://xionny.cn/topic/hpcompaqipaq/ hp-compaq-ipaq 6345] [http://polex.com.cn/resources/articles/sennheiser-.htm sennheiser - cuffia senza filo] [http://wedner.info/content/view/dvd-d.htm dvd 110d pioneer] [http://klohy.info/img/styles/gli-stadio.htm gli stadio] [http://veggis.org.cn/resources/articles/live-in.htm live in japan] [http://klohy.info/img/styles/racconti-strip.htm racconti strip poker] [http://funkall.us/images/small/lavastoviglie-da/ lavastoviglie da 45 cm] [http://soler.net.cn/data/amd-sempron.htm amd sempron 3400] [http://funkall.us/images/small/microsoft-starck/ microsoft starck mouse] [http://xionny.cn/topic/first-day/ first day of my life] [http://joperan.org/data/assicurazione-san/ assicurazione san donato milanese] [http://klohy.info/img/styles/this-love.htm this love di marron 5] [http://primonona.info/content/view/codici-sblocco/ codici sblocco nec e313] [http://klohy.info/img/styles/diffusori-infinity.htm diffusori infinity casse acustiche] [http://budget7i.info/lib/televisori-al/ televisori al plasma 42 xga] [http://polex.com.cn/resources/articles/whirlpool-akm.htm whirlpool akm373] [http://klohy.info/img/styles/gigaset-siemens.htm gigaset siemens cordless] [http://manoke.cn/topic/libri-di/ libri di sesso] [http://veggis.org.cn/resources/articles/peccato-carnale.htm peccato carnale] [http://manoke.cn/topic/monitor-portatile/ monitor portatile] [http://polex.com.cn/resources/articles/porno-fuerte.htm porno fuerte] [http://xionny.cn/topic/deseo-ver/ deseo ver porno] [http://budget7i.info/lib/viideo-chat/ viideo chat] [http://joperan.org/data/cefalu/ cefalu 2005] [http://sneck.info/data/casa-riposo/ casa riposo brentonico] [http://xionny.cn/topic/pentium-dual/ pentium dual core] [http://sneck.info/data/toshiba-mx/ toshiba m40x - 269] [http://polex.com.cn/resources/articles/sono-pia.htm sono pia sereno] [http://sneck.info/data/anche-postal/ anche postal approda sul grande schermo] [http://sneck.info/data/tennis-roland/ tennis roland garros] [http://soler.net.cn/data/responsabile-commerciale.htm responsabile commerciale italia (regione emilia romagna - bologna provincia)] [http://funkall.us/images/small/www-playstation/ www playstation it] [http://sneck.info/data/trova-film/ trova film citta] [http://primonona.info/content/view/www-selen/ www selen com] [http://budget7i.info/lib/il-marchio/ il marchio del bruto] [http://soler.net.cn/data/milano-appartamento.htm milano appartamento] [http://primonona.info/content/view/hotel-/ hotel 5 stella cannes] [http://xionny.cn/topic/qtek-/ qtek 1010 gps] [http://klohy.info/img/styles/you-can.htm you can] [http://funkall.us/images/small/l-odio/ l odio colonna sonora] [http://klohy.info/img/styles/ristorante-messicano.htm ristorante messicano] [http://polex.com.cn/resources/articles/pca.htm pca] [http://funkall.us/images/small/tose/ tose] [http://xionny.cn/topic/cavo-audio/ cavo audio coassiale monster] [http://wedner.info/content/view/hama-lettore.htm hama lettore 9 in 1] [http://primonona.info/content/view/jbl-northridge/ jbl northridge e 150p] [http://svike.info/view/new/canvas-professional.htm canvas professional edition] [http://manoke.cn/topic/be-it/ be2 it] [http://sneck.info/data/lg-rh/ lg rh] [http://wedner.info/content/view/caboblanco.htm caboblanco] [http://sneck.info/data/nokia-con/ nokia con radio fm] [http://polex.com.cn/resources/articles/joy-kitikonti.htm joy kitikonti dirty summer dirty mix] [http://primonona.info/content/view/whipping/ whipping] {{task}}
{{task}}
Demonstrates how to implement a custom IsNumeric method.
 
Line 50:
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]]==
[[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.
Anonymous user