Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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 8-Jan-13 0:52am
Edited 8-Jan-13 0:57am
v2
Comments
Zoltán Zörgő at 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.
glennPattonWork at 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ő at 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 at 8-Jan-13 8:04am
   
I totally agree. RegEx is not from hell. It's very powerfull and a great tool.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You could use a regex to ensure they are all digits, or you could just use int.TryParse:
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.
  Permalink  
Comments
glennPattonWork at 8-Jan-13 7:07am
   
Thanks for that! I'll give it a go!
jibesh at 8-Jan-13 11:28am
   
my 5+
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

The routine I use is:
 
    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:
 
      if (IsNumeric(myString.Substring(4, 5))
      {
            // success
      }
 
Or to test a full string:
 
      if (IsNumeric(myString)
      {
            // success
      }
  Permalink  
v4
Comments
glennPattonWork at 8-Jan-13 7:25am
   
Thanks Alot! Seems to doing the job!!
Glenn
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Just to give you a hint, how you could solve it using Regex...
 
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);
    }
}
 
  Permalink  
Comments
glennPattonWork at 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 at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

Hi.
You can try also
 

public static bool IsOnlyDigits1(string text)
{
    foreach (char ch in text)
    {
        if (!char.IsDigit(ch))
            return false;
    }
 
    return true;
}
 
public static bool IsOnlyDigits2(string text)
{
    for (int nIndex = 0; nIndex < text.Length; nIndex++)
    {
        if (!char.IsDigit(text, nIndex))
            return false;
    }
 
    return true;
}
 
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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

Those are all good solutions. Here's a very clean one to parse your serial number per the requirements you gave.
 
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.");
        }
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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
  Permalink  

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

  Print Answers RSS
0 CPallini 550
1 Sergey Alexandrovich Kryukov 420
2 George Jonsson 288
3 Pheonyx 218
4 OriginalGriff 200
0 OriginalGriff 4,813
1 CPallini 3,850
2 Sergey Alexandrovich Kryukov 3,224
3 George Jonsson 2,552
4 Gihan Liyanage 2,186


Advertise | Privacy | Mobile
Web02 | 2.8.140905.1 | Last Updated 8 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100