Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi All,

I am trying to convert a string to an int but have come across a twist with the way I am doing it. I am using C# and a serial number is read in as a string. I am then checking it's length with the string property .Length to ensure it is 8 characters to short or too long errors. That is working I now what to check it is numeric (between 0 - 9) I was thinking of doing a Convert.ToInt(32) to check if its a number if it contains characters of than 0-9 it errors, I would like to know the correct way of doing this as if I use a try catch it seems a little heavy handed? Is there a IsNumeric type command ? (or a I being poisned by script again!)
Glenn
I have in thinking/googling found Davey69's Simple Numeric Text Box at
Simple Numeric TextBox[^] but it does seem a not quite right for my purpose.
Posted
Updated 8-Jan-13 0:57am
v2
Comments
Zoltán Zörgő 8-Jan-13 6:56am    
I am pretty sure you need regular experssion to check the syntax. But Without a proper format (some sample strings to validate), it will be hard to have any suggestion.
glennPattonWork3 8-Jan-13 7:04am    
Ooh 'eck RegEx again! it just needs to look at the data if it's too short or too long it throws it away (ie. 12345678 is good 1234567890 in not and neither is 123) using this method it traps everything but 1234567a which then get it self in a mess later

Zoltán Zörgő 8-Jan-13 7:10am    
Well, it's up to you. But RegEx is not from devil. It can go really complicated, but it is a handy tool for simple syntax check also. I suggest you get familiar with it. Sooner or later you will not be able to avoid it, or you will waste too much resources on something that's a two-line code with regexp...
Andy411 8-Jan-13 8:04am    
I totally agree. RegEx is not from hell. It's very powerfull and a great tool.

You could use a regex to ensure they are all digits, or you could just use int.TryParse:
C#
string serial = "98765432";
int serialNo;
if (int.TryParse(serial, out serialNo))
    {
    Console.WriteLine(serialNo);
    }
The only thing you might want to add is a Trim to the input, as TryParse will not fail on numbers starting and / or ending with whitespace.
 
Share this answer
 
Comments
glennPattonWork3 8-Jan-13 7:07am    
Thanks for that! I'll give it a go!
Jibesh 8-Jan-13 11:28am    
my 5+
The routine I use is:

C#
public System.Boolean IsNumeric(System.Object Expression)
{
    if(Expression == null || Expression is DateTime)
        return false;

    if(Expression is Int16 || Expression is Int32 ||
        Expression is Int64 || Expression is Decimal ||
        Expression is Single || Expression is Double ||
        Expression is Boolean)
        return true;

    try
    {
        if(Expression is string)
            Double.Parse(Expression as string);
        else
            Double.Parse(Expression.ToString());

            return true;
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.Message);
    }

    return false;
}


So to test a character in a string, for example, you can then write:

C#
if (IsNumeric(myString.Substring(4, 5))
{
      // success
}


Or to test a full string:

C#
if (IsNumeric(myString)
{
      // success
}
 
Share this answer
 
v4
Comments
glennPattonWork3 8-Jan-13 7:25am    
Thanks Alot! Seems to doing the job!!
Glenn
Just to give you a hint, how you could solve it using Regex...

C#
string serial = "12345678";  

string pattern = @"^\d{8}$";
Regex rx = new Regex(pattern);

if (rx.IsMatch(serial))
{
    int nr = 0;
    if( int.TryParse(serial, out nr))
    {
        Console.WriteLine(nr);
    }
}
 
Share this answer
 
Comments
glennPattonWork3 8-Jan-13 8:14am    
I will have to give it a go, after lunch. Is there a good (simple) refernce other than the MSDN page I seem to remember it giving me cold chills and the feeling was doing more than it should!
Glenn
Andy411 8-Jan-13 8:36am    
Well, I did it the "hard way" and a lot of trial and error. Sometimes this http://regexhero.net/tester/ is helpfull
Hi.
You can try also


C#
public static bool IsOnlyDigits1(string text)
{
    foreach (char ch in text)
    {
        if (!char.IsDigit(ch))
            return false;
    }

    return true;
}


C#
public static bool IsOnlyDigits2(string text)
{
    for (int nIndex = 0; nIndex < text.Length; nIndex++)
    {
        if (!char.IsDigit(text, nIndex))
            return false;
    }

    return true;
}


C#
using System.Globalization;

public static bool IsOnlyDigits3(string text)
{
    Int32 nTest
    if (!Int32.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture,
        out nTest))
        return false;

    return true;
}


The two functions using char.IsDigit should be the lightest possible.
The third ensures no decimal point or sign being accepted.

Regards,
Daniele.
 
Share this answer
 
Those are all good solutions. Here's a very clean one to parse your serial number per the requirements you gave.

C#
public static int ParseSerialNumber(string num)
        {
            if (num.Count(n => char.IsDigit(n)) == 8 && num.Count(n => !char.IsDigit(n)) == 0)
                return int.Parse(num);
            else
                throw new ArgumentOutOfRangeException("This is not an 8 digit number.");
        }
 
Share this answer
 
Thanks to all I have now solved this issue and sent the code off however I am going to be poking around with all methods suggested here as there are some I hadn't come up seen before. I probably will bother you all with RegEx questions later.
Thanks All
Glenn
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900