Author Topic: IsNumeric in C#  (Read 8144 times)

0 Members and 1 Guest are viewing this topic.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
IsNumeric in C#
« on: April 18, 2007, 09:09:56 PM »
C# does not have a IsNumeric method.
Vb.net does, but I didn't want to include the vb dll and all that comes with it.

MS help has an option involving TryParse that seems to do the job.
http://support.microsoft.com/kb/329488
Article ID : 329488
Last Review : December 11, 2006

The comments make it appear more complicated than it is.

Code: [Select]
static bool IsNumeric(object Expression)
{
    // Variable to collect the Return value of the TryParse method.
    bool isNum;

    // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
    double retNum;

    // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
    // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
    isNum = Double.TryParse(Convert.ToString(Expression),
                            System.Globalization.NumberStyles.Any,
                            System.Globalization.NumberFormatInfo.InvariantInfo,
                            out retNum );
    return isNum;
}
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

LE

  • Guest
Re: IsNumeric in C#
« Reply #1 on: April 18, 2007, 09:32:58 PM »
I think - (lately not much) - that here we can use regular expresions - I guess...

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #2 on: April 18, 2007, 09:37:48 PM »
Yes my search came across a regex solution .. but accounting for negative numbers and Localisation seemed an issue.

Code: [Select]
public static bool IsNumeric(string theValue)
{
   Regex _isNumber = new Regex(@"^\d+$");
   Match m = _isNumber.Match(theValue);
   return m.Success;
}
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Glenn R

  • Guest
Re: IsNumeric in C#
« Reply #3 on: April 18, 2007, 09:39:43 PM »
Are you trying to test a character and determine if it's numeric? If so char.IsNumber() from memory...if not, ignore me. :)

LE

  • Guest
Re: IsNumeric in C#
« Reply #4 on: April 18, 2007, 09:41:25 PM »
I see that Glenn... came up with something that sound to easy....

While that can be, how about something like this, Kerry:

Code: [Select]
string strNum;
Regex oPattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
oPattern.IsMatch(strNum);

Without any test....

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #5 on: April 18, 2007, 09:43:03 PM »
NO, I won't ignore you. ! ;-)

I was looking for a test for a string.

Think of say extracting Text, Mtext and Dimension values and attempting to add <sum> the values.


added: qualified the add
« Last Edit: April 18, 2007, 09:46:18 PM by Kerry Brown »
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Glenn R

  • Guest
Re: IsNumeric in C#
« Reply #6 on: April 18, 2007, 09:46:01 PM »
Well, if it's a STRING and you're trying to convert to some type of number, then yourPreferredNumbericTypeHere.TryParse() is probably the best shot.

Glenn R

  • Guest
Re: IsNumeric in C#
« Reply #7 on: April 18, 2007, 09:47:07 PM »
Or like Luis said - regex are pretty damn useful, but definately a black art.

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8743
  • AKA Daniel
Re: IsNumeric in C#
« Reply #8 on: April 18, 2007, 09:51:20 PM »
If you compile the VB method, what does reflector show?

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #9 on: April 18, 2007, 09:54:21 PM »
............. how about something like this, Kerry:

Code: [Select]
string strNum;
Regex oPattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
oPattern.IsMatch(strNum);

Without any test....

That looks interesting Luis .. I'd have to test it.
As Glenn mentioned Regex is a bit like magic ... the way it works is not immediately obvious .. not that that would matter once it's tested.

*smack use spellcheck, dummy
« Last Edit: April 18, 2007, 10:03:30 PM by Kerry Brown »
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #10 on: April 18, 2007, 09:55:25 PM »
If you compile the VB method, what does reflector show?

Don't laugh ....
Code: [Select]
public static bool IsNumeric(object Expression)
{
    double result;
    IConvertible convertible = Expression as IConvertible;
    if (convertible == null)
    {
        char[] chArray = Expression as char[];
        if (chArray == null)
        {
            return false;
        }
        Expression = new string(chArray);
    }
    TypeCode typCode = convertible.GetTypeCode();
    if ((typCode != TypeCode.String) && (typCode != TypeCode.Char))
    {
        return IsOldNumericTypeCode(typCode);
    }
    string text = convertible.ToString(null);
    try
    {
        long num2;
        if (Utils.IsHexOrOctValue(text, ref num2))
        {
            return true;
        }
    }
    catch (StackOverflowException exception)
    {
        throw exception;
    }
    catch (OutOfMemoryException exception2)
    {
        throw exception2;
    }
    catch (ThreadAbortException exception3)
    {
        throw exception3;
    }
    catch (Exception)
    {
        return false;
    }
    return DoubleType.TryParse(text, ref result);
}
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

LE

  • Guest
Re: IsNumeric in C#
« Reply #11 on: April 18, 2007, 10:23:23 PM »
Creo que Glenn se referia a algo asi, que esta integrado en C#...

Code: [Select]
public bool isNumeric(string val, NumberStyles NumberStyle)
{
    Double result;
    return Double.TryParse(val, NumberStyle, CultureInfo.CurrentCulture, out result);
}

Quote
string strNum1 = "0231.3213", strNum2 = "asad1213.34", strNum3 = ".2342314", strNum4 = "ADSAD", strNum5 = "-1";
if (isNumeric(strNum1, NumberStyles.Number)) //(IsNumber(strNum1) == true)
    ed.WriteMessage("\n" + strNum1 + " is a number!\n");
else
    ed.WriteMessage(strNum1 + " is not a number!\n");

if (isNumeric(strNum2, NumberStyles.Number))
    ed.WriteMessage(strNum2 + " is a number!\n");
else
    ed.WriteMessage(strNum2 + " is not a number!\n");

if (isNumeric(strNum3, NumberStyles.Number))
    ed.WriteMessage(strNum3 + " is a number!\n");
else
    ed.WriteMessage(strNum3 + " is not a number!\n");

if (isNumeric(strNum4, NumberStyles.Number))
    ed.WriteMessage(strNum4 + " is a number!\n");
else
    ed.WriteMessage(strNum4 + " is not a number!\n");

if (isNumeric(strNum5, NumberStyles.Number))
    ed.WriteMessage(strNum5 + " is a number!\n");
else
    ed.WriteMessage(strNum5 + " is not a number!\n");

Quote
0231.3213 is a number!
asad1213.34 is a number!
.2342314 is a number!
ADSAD is not a number!
-1 is a number!
[/qoute]
« Last Edit: April 18, 2007, 10:25:36 PM by LE »

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #12 on: April 18, 2007, 10:31:24 PM »
Luis, that's essentially the solution I posted. yes ?

or an overloaded version anyway, for a specific NumberStyle .. good idea.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: IsNumeric in C#
« Reply #13 on: April 18, 2007, 10:33:01 PM »
Quote
asad1213.34 is a number!

????
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

LE

  • Guest
Re: IsNumeric in C#
« Reply #14 on: April 18, 2007, 10:35:09 PM »
Quote
asad1213.34 is a number!

????

That was the output for the regex... sorry, give it a try and should work...