Determine if a string is numeric: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 1: Line 1:
{{task}}
[http://students.hsc.unt.edu/housing/item.cfm?type=2878 cheap sildenafil] [http://students.hsc.unt.edu/housing/item.cfm?type=2902 free nextel ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=357 funny ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1347 cheap cialis] [http://library.cshl.edu/wp/vb/member.php?u=1365 ultracet online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=210 free sprint ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=158 cheap diazepam] [http://wc1.worldcrossing.com/WebX/.1de609ea free free ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a25 samsung ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=88 free free ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1358 hydrocodone online] [http://library.cshl.edu/wp/vb/member.php?u=1339 tramadol online] [http://students.hsc.unt.edu/housing/item.cfm?type=2868 ambien online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=228 mtv ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=104 free motorola ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=89 funny ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=211 music ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=80 free cool ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1388 cheap fioricet] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=361 real ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=172 lorazepam] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=333 soma online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=182 clomid online] [http://library.cshl.edu/wp/vb/member.php?u=1355 cheap clonazepam] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=205 paxil online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=184 lisinopril online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=124 samsung ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a04 sonyericsson ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=115 cheap phentermine] [http://library.cshl.edu/wp/vb/member.php?u=1387 free alltel ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a05 free sprint ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=167 cheap clonazepam] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30283 didrex online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=157 ultram online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=230 free verizon ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30309 celexa online] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=348 but norco] [http://wc1.worldcrossing.com/WebX/.1de60a11 buy diethylpropion] [http://news.engin.brown.edu/forums/thread-view.asp?tid=188 tenuate online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=212 verizon ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30308 lipitor online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=82 diazepam online] [http://library.cshl.edu/wp/vb/member.php?u=1380 free verizon ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=163 cheap adipex] [http://students.hsc.unt.edu/housing/item.cfm?type=2859 meridia online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=209 samsung ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=170 cingular ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=78 clomid] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30298 order lisinopril] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=74 cheap carisoprodol] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=352 paxil online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=227 free ericsson ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1386 mono ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=69 albuterol online] [http://wc1.worldcrossing.com/WebX/.1de60a12 ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=171 ambien online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=188 levitra online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=83 cheap didrex] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30358 free midi ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2879 clomid online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=186 cheap lipitor] [http://news.engin.brown.edu/forums/thread-view.asp?tid=215 sagem ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=346 meridia online] [http://students.hsc.unt.edu/housing/item.cfm?type=2923 free sony ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30237 cheap valium] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=171 order clomid] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=184 hoodia] [http://wc1.worldcrossing.com/WebX/.1de60a1b music ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30264 hydrocodone] [http://wc1.worldcrossing.com/WebX/.1de609db but adipex] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30321 hgh online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=90 cheap hgh] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30263 cheap levitra] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=133 free tracfone ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=226 free sony ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=117 propecia online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=165 cheap vicodin] [http://library.cshl.edu/wp/vb/member.php?u=1340 cheap soma] [http://students.hsc.unt.edu/housing/item.cfm?type=2909 verizon ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30252 buy meridia] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=221 vicodin online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30347 verizon ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1354 cheap alprazolam] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30330 nokia ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2903 free qwest ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a26 free sharp ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30348 free polyphonic ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=345 viagra online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=239 cheap sildenafil] [http://students.hsc.unt.edu/housing/item.cfm?type=2876 buy didrex] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=142 wellbutrin] [http://students.hsc.unt.edu/housing/item.cfm?type=2872 online cyclobenzaprine] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30333 funny ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a00 rivotril online] [http://library.cshl.edu/wp/vb/member.php?u=1356 order paxil] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30357 free sharp ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=123 free sagem ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30268 order xenical] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=92 hydrocodone online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=100 lortab online] [http://students.hsc.unt.edu/housing/item.cfm?type=2850 phentermine online] [http://students.hsc.unt.edu/housing/item.cfm?type=2869 cheap lorazepam] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=116 polyphonic ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1361 cheap xenical] [http://library.cshl.edu/wp/vb/member.php?u=1362 buy wellbutrin] [http://wc1.worldcrossing.com/WebX/.1de60a2b cheap ultracet] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=113 paxil online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30279 cheap ultracet] [http://news.engin.brown.edu/forums/thread-view.asp?tid=229 free jazz ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2863 alprazolam online] [http://wc1.worldcrossing.com/WebX/.1de609f4 free mono ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1353 vicodin] [http://students.hsc.unt.edu/housing/item.cfm?type=2880 albuterol online] [http://wc1.worldcrossing.com/WebX/.1de609eb funny ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=181 free free ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2887 cheap pharmacy online] [http://library.cshl.edu/wp/vb/member.php?u=1364 cheap nexium] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=222 cheap vigrx] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=166 buy ativan] [http://library.cshl.edu/wp/vb/member.php?u=1381 free polyphonic ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=180 flexeril online] [http://wc1.worldcrossing.com/WebX/.1de609fd free punk ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=102 midi ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a2c but ultram] [http://students.hsc.unt.edu/housing/item.cfm?type=2853 cheap fioricet] [http://students.hsc.unt.edu/housing/item.cfm?type=2899 tracfone ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=185 cheap hydrocodone] [http://library.cshl.edu/wp/vb/member.php?u=1378 sprint ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1350 cheap meridia] [http://news.engin.brown.edu/forums/thread-view.asp?tid=152 cheap valium] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=208 cheap phentermine] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=349 vicodin online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=77 cingular ringtones] [http://wc1.worldcrossing.com/WebX/.1de60a0c wellbutrin online] [http://students.hsc.unt.edu/housing/item.cfm?type=2860 cheap adipex] [http://news.engin.brown.edu/forums/thread-view.asp?tid=223 midi ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=126 cheap sildenafil] [http://library.cshl.edu/wp/vb/member.php?u=1383 free sagem ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=197 cheap flexeril] [http://students.hsc.unt.edu/housing/item.cfm?type=2898 free ringtones] [http://wc1.worldcrossing.com/WebX/.1de609ff real ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30336 free qwest ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=343 cialis] [http://students.hsc.unt.edu/housing/item.cfm?type=2924 ericsson ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=183 online albuterol] [http://library.cshl.edu/wp/vb/member.php?u=1342 cheap phentermine] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=220 real ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2883 lipitor online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=203 funny ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=73 ativan online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=218 qwest ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=202 free tracfone ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=96 levitra online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=105 mp3 ringtones] [http://library.cshl.edu/wp/vb/member.php?u=1375 free real ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30238 phentermine online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30355 free punk ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30349 free cingular ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=199 free music ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2914 sony ericsson ringtones] [http://wc1.worldcrossing.com/WebX/.1de609e7 cheap diazepam] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30315 buy lortab] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=143 wwe ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2906 free samsung ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=174 cheap cyclobenzaprine] [http://wc1.worldcrossing.com/WebX/.1de60a03 sony ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2857 ativan online] [http://wc1.worldcrossing.com/WebX/.1de60a2d cheap valium] [http://students.hsc.unt.edu/housing/item.cfm?type=2856 cialis online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30242 cheap fioricet] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=160 order adipex] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=232 free sony ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2900 funny ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2870 xenical online] [http://news.engin.brown.edu/forums/thread-view.asp?tid=150 order tramadol] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30332 tracfone ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30354 alltel ringtones] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=202 nokia ringtones] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=134 tramadol online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=167 carisoprodol online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30269 wellbutrin online] [http://students.hsc.unt.edu/housing/item.cfm?type=2893 hgh online] [http://itcweb.ecsu.edu/portal/forums.asp?ForumId=13&TopicId=219 viagra online] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30240 cheap carisoprodol] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30316 order vigrx] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30351 free sonyericsson ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30350 free sagem ringtones] [http://www.psfc.mit.edu/~jinseok/bbse/view.php?id=presentations&no=332 order tramadol] [http://students.hsc.unt.edu/housing/item.cfm?type=2925 free mtv ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2915 free mono ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30359 wwe ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2849 valium] [http://students.hsc.unt.edu/housing/item.cfm?type=2867 order hydrocodone] [http://wc1.worldcrossing.com/WebX/.1de60a16 levitra online] [http://library.cshl.edu/wp/vb/member.php?u=1379 music ringtones] [http://students.hsc.unt.edu/housing/item.cfm?type=2919 sharp ringtones] [http://www.e.kth.se/cgi-bin/esekt/discussion?command=read&discussionid=4&id=30338 motorola ringtones] [http://news.engin.brown.edu/forums/thread-view.asp?tid=174 wellbutrin online] [http://www.ees.ufl.edu/alumni/forums.asp?ForumId=5&TopicId=84 cheap diethylpropion] [http://students.hsc.unt.edu/housing/item.cfm?type=2882 zoloft online] {{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>

==[[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 05:33, 15 July 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>

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.