Determine if a string is numeric

Revision as of 02:43, 25 January 2007 by 69.238.90.83 (talk) (→‎[[Java]])

Demonstrates how to implement a custom IsNumeric method in other .NET/Mono languages that do not wish to reference the Microsoft.VisualBasic.dll assembly.

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.

C#

Compiler: Microsoft (R) Visual C# 2005 Compiler version 8.00


public static bool IsNumeric(string s)
{
    double Result;
    return double.TryParse(s, out Result);
}        

string value = "123";
if (IsNumeric(value)) 
{
  // do something
}

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>

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;
  }
}

mIRC

var %value = 3
if ($1 isnum) {
  echo -s $1 is 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?)

Visual Basic .NET

Compiler: Microsoft (R) Visual Basic Compiler version 8.0

Dim Value As String = "123"
If IsNumeric(Value) Then
    
End If