Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Checking if a value is an integer

Checking if a value is an integer

Scheduled Pinned Locked Moved C#
question
16 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M mav northwind

    Yes there is a better way: Double.TryParse()[^] Regards, mav

    A Offline
    A Offline
    Andy M
    wrote on last edited by
    #5

    A double is no use to me. It will accept as valid values that are not valid integers. It is a pity, however, that there doesn't seem to be an equivalent for Int32.

    M 1 Reply Last reply
    0
    • A Andy M

      I have a string that contains some text. I want to check if the text can be converted into an integer. At the moment my code looks like this:

      bool isInt = true;
      try
      {
      int intValue = int.Parse(stringValue);
      }
      catch(Exception e)
      {
      isInt = false;
      }

      At the end of the code isInt will contain whether the string value can be converted to an int or not. Is there a better way to do this? I don't like having to catch an exception when I expect that many string values will not be convertable to an int. It seems very inefficient.

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #6

      Try Convert.ToInt32() or Use a TypeConvertor by calling TypeDescriptor.GetConvertor(typeof(int)) xacc-ide 0.0.15 now with C#, MSIL, C, XML, ASP.NET, Nemerle, MyXaml and HLSL coloring - Screenshots

      1 Reply Last reply
      0
      • A Andy M

        I have a string that contains some text. I want to check if the text can be converted into an integer. At the moment my code looks like this:

        bool isInt = true;
        try
        {
        int intValue = int.Parse(stringValue);
        }
        catch(Exception e)
        {
        isInt = false;
        }

        At the end of the code isInt will contain whether the string value can be converted to an int or not. Is there a better way to do this? I don't like having to catch an exception when I expect that many string values will not be convertable to an int. It seems very inefficient.

        J Offline
        J Offline
        Judah Gabriel Himango
        wrote on last edited by
        #7

        I don't know how fast this is compared to the other options, but this way won't throw any exceptions, which are inefficient. Using regular expressions to validate input is a common practice:

        bool isNumber = System.Text.RegularExpressions.Regex.IsMatch(stringValue, "[0-9]");

        Tech, life, family, faith: Give me a visit. I'm currently blogging about: Conversation With a Muslim Judah Himango

        M 1 Reply Last reply
        0
        • J Judah Gabriel Himango

          I don't know how fast this is compared to the other options, but this way won't throw any exceptions, which are inefficient. Using regular expressions to validate input is a common practice:

          bool isNumber = System.Text.RegularExpressions.Regex.IsMatch(stringValue, "[0-9]");

          Tech, life, family, faith: Give me a visit. I'm currently blogging about: Conversation With a Muslim Judah Himango

          M Offline
          M Offline
          Matt Gerrans
          wrote on last edited by
          #8

          But you have to be careful with regular expressions, since they are only testing what you think should be a valid int, not what really may be valid. For example, the regular expression you offered won't do too well on negative values. Matt Gerrans

          1 Reply Last reply
          0
          • A Andy M

            I have a string that contains some text. I want to check if the text can be converted into an integer. At the moment my code looks like this:

            bool isInt = true;
            try
            {
            int intValue = int.Parse(stringValue);
            }
            catch(Exception e)
            {
            isInt = false;
            }

            At the end of the code isInt will contain whether the string value can be converted to an int or not. Is there a better way to do this? I don't like having to catch an exception when I expect that many string values will not be convertable to an int. It seems very inefficient.

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #9

            What would be better is just catching an InvalidCastException, instead of anything that may go wrong. Christian Graus - Microsoft MVP - C++

            A 1 Reply Last reply
            0
            • A Andy M

              A double is no use to me. It will accept as valid values that are not valid integers. It is a pity, however, that there doesn't seem to be an equivalent for Int32.

              M Offline
              M Offline
              mav northwind
              wrote on last edited by
              #10

              I suggest you actually read the documentation. There's a flag controlling what kind of numbers to parse. mav

              A 1 Reply Last reply
              0
              • L Lost User

                It's the most secure way to convert a string to an int. Why don't you put just all assignments into one single try-catch block? regards

                A Offline
                A Offline
                Andy M
                wrote on last edited by
                #11

                Since someone voted my previous reply a 3 I can only guess that I didn't explain myself very well. I don't have multiple assignments. I only want to check one value and I only want to check if it is possible to convert it to an integer. I do not want to do an actual conversion. If further explanation is needed, I'll be happy to explain more.

                1 Reply Last reply
                0
                • M mav northwind

                  I suggest you actually read the documentation. There's a flag controlling what kind of numbers to parse. mav

                  A Offline
                  A Offline
                  Andy M
                  wrote on last edited by
                  #12

                  mav.northwind wrote: I suggest you actually read the documentation. I did read the documentation, but it does not explain on the TryParse page that it can be used to check integers. That is pretty useless documentation if you have to delve into sub-documents to find something that should have been at least mentioned on the first page even if there was no details about it. Thank you for at least prodding me to read further because I did eventaully find the answer on this route. I hope you don't mind my little rant at the documentation. MSDN is usually very good.

                  M 1 Reply Last reply
                  0
                  • C Christian Graus

                    What would be better is just catching an InvalidCastException, instead of anything that may go wrong. Christian Graus - Microsoft MVP - C++

                    A Offline
                    A Offline
                    Andy M
                    wrote on last edited by
                    #13

                    Thanks for your suggestion, I realise that I should only catch the specific case. However, I don't expect the failure of the conversion to be an exceptional case. I expect that the string does not conform regularly. That is why I didn't want to use a method that throws exceptions when the conversion fails. I got an answer about Double.TryParse that returns a Boolean value and can be set to convert only integers that I'm going to use.

                    C 1 Reply Last reply
                    0
                    • A Andy M

                      mav.northwind wrote: I suggest you actually read the documentation. I did read the documentation, but it does not explain on the TryParse page that it can be used to check integers. That is pretty useless documentation if you have to delve into sub-documents to find something that should have been at least mentioned on the first page even if there was no details about it. Thank you for at least prodding me to read further because I did eventaully find the answer on this route. I hope you don't mind my little rant at the documentation. MSDN is usually very good.

                      M Offline
                      M Offline
                      mav northwind
                      wrote on last edited by
                      #14

                      Glad to hear you found the information. The NumberStyles enumeration is in fact not explained on the page of TryParse, but that's the standard way MSDN is built. It's a separate type, so it's documented separately. With a proper link, though. Anyway, once you actually have found the information you needed it's usually there where you'd expect it to be. But the location is only obvious _after_ you've found it, not when you're actually trying to find it :rolleyes: mav

                      1 Reply Last reply
                      0
                      • A Andy M

                        Thanks for your suggestion, I realise that I should only catch the specific case. However, I don't expect the failure of the conversion to be an exceptional case. I expect that the string does not conform regularly. That is why I didn't want to use a method that throws exceptions when the conversion fails. I got an answer about Double.TryParse that returns a Boolean value and can be set to convert only integers that I'm going to use.

                        C Offline
                        C Offline
                        Christian Graus
                        wrote on last edited by
                        #15

                        Andy MacAngus wrote: However, I don't expect the failure of the conversion to be an exceptional case. Exceptions don't mean you can only use them when they will rarely throw. Andy MacAngus wrote: Double.TryParse Yeah, I thought there was something like that, but couldn't remember the details. Christian Graus - Microsoft MVP - C++

                        A 1 Reply Last reply
                        0
                        • C Christian Graus

                          Andy MacAngus wrote: However, I don't expect the failure of the conversion to be an exceptional case. Exceptions don't mean you can only use them when they will rarely throw. Andy MacAngus wrote: Double.TryParse Yeah, I thought there was something like that, but couldn't remember the details. Christian Graus - Microsoft MVP - C++

                          A Offline
                          A Offline
                          Andy M
                          wrote on last edited by
                          #16

                          Christian Graus wrote: Exceptions don't mean you can only use them when they will rarely throw. What I mean is that exceptions are expensive and I expect that in the validation code I am writing that there will be a lot of bad data and I would like the validation code to work quickly. :)

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups