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. Removing leading zeros from negative string

Removing leading zeros from negative string

Scheduled Pinned Locked Moved C#
20 Posts 8 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 Offline
    M Offline
    mprice214
    wrote on last edited by
    #1

    Hi all, Is there a straight forward way to remove leading zeros from a negative string: ex. -00002 -> -2 Thanks.

    D L P J 4 Replies Last reply
    0
    • M mprice214

      Hi all, Is there a straight forward way to remove leading zeros from a negative string: ex. -00002 -> -2 Thanks.

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #2

      Depends on what you're trying to do, but you can always use Integer.Parse or Integer.TryParse to convert it to an int, then just format it however you want with .ToString.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
           2006, 2007, 2008
      But no longer in 2009...

      M 1 Reply Last reply
      0
      • M mprice214

        Hi all, Is there a straight forward way to remove leading zeros from a negative string: ex. -00002 -> -2 Thanks.

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        sounds like you want a regex, replacing a minus and zero or more zeroes, by a minus sign. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        Prolific encyclopedia fixture proof-reader browser patron addict?
        We all depend on the beast below.


        1 Reply Last reply
        0
        • D Dave Kreskowiak

          Depends on what you're trying to do, but you can always use Integer.Parse or Integer.TryParse to convert it to an int, then just format it however you want with .ToString.

          A guide to posting questions on CodeProject[^]
          Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
               2006, 2007, 2008
          But no longer in 2009...

          M Offline
          M Offline
          mprice214
          wrote on last edited by
          #4

          That worked great. Is there an easy way that I can see how much processing time the parsing is adding to the loop?

          A R 2 Replies Last reply
          0
          • M mprice214

            That worked great. Is there an easy way that I can see how much processing time the parsing is adding to the loop?

            A Offline
            A Offline
            AspDotNetDev
            wrote on last edited by
            #5

            Do the processing without the parsing a bunch of times, take the average time. Compare that to the average time of doing the processing with the parsing.

            [Forum Guidelines]

            1 Reply Last reply
            0
            • M mprice214

              Hi all, Is there a straight forward way to remove leading zeros from a negative string: ex. -00002 -> -2 Thanks.

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #6

              Or repeatedly replace "-0" with "-" until there are none. X| Or make substrings of the first character and all the rest, left trim the zeroes from the second part, and concatenate.

              1 Reply Last reply
              0
              • M mprice214

                Hi all, Is there a straight forward way to remove leading zeros from a negative string: ex. -00002 -> -2 Thanks.

                J Offline
                J Offline
                jaypatel512
                wrote on last edited by
                #7

                Have you tried Convert.ToInt32(-00002); This might get you rid of everything, even though the input is a negative number. - jaypatel512

                P 1 Reply Last reply
                0
                • J jaypatel512

                  Have you tried Convert.ToInt32(-00002); This might get you rid of everything, even though the input is a negative number. - jaypatel512

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #8

                  <rant>DON'T USE THE CONVERT CLASS!!!</rant> Pretty much all it does is call the appropriate xxx.Parse method anyway, so if you know what class it is, just call its Parse method, Int32.Parse, as was already mentioned. The only reasonable member of Convert is ChangeType.

                  P 1 Reply Last reply
                  0
                  • M mprice214

                    That worked great. Is there an easy way that I can see how much processing time the parsing is adding to the loop?

                    R Offline
                    R Offline
                    Ravi Bhavnani
                    wrote on last edited by
                    #9

                    Yes.  See the Stopwatch[^] class. /ravi

                    My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                    1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      <rant>DON'T USE THE CONVERT CLASS!!!</rant> Pretty much all it does is call the appropriate xxx.Parse method anyway, so if you know what class it is, just call its Parse method, Int32.Parse, as was already mentioned. The only reasonable member of Convert is ChangeType.

                      P Offline
                      P Offline
                      Paw Jershauge
                      wrote on last edited by
                      #10

                      Never ever use Parse if there is an TryParse method. thats best pratice and will alway be ;) ;) ;)

                      With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                      P 1 Reply Last reply
                      0
                      • P Paw Jershauge

                        Never ever use Parse if there is an TryParse method. thats best pratice and will alway be ;) ;) ;)

                        With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #11

                        Only when it's available. Or, if you want the Exception to be thrown. Why avoid the Exception if you're just going to throw your own anyway?

                        P 1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          Only when it's available. Or, if you want the Exception to be thrown. Why avoid the Exception if you're just going to throw your own anyway?

                          P Offline
                          P Offline
                          Paw Jershauge
                          wrote on last edited by
                          #12

                          PIEBALDconsult wrote:

                          Only when it's available.

                          thats what i said ;) (if the method is there...) Now why would you even consider raising/throwing an exception, thats just bad pratice. never use exception for you code-flow. An exception should only be thrown, when it truly is an exception, like if your transfer data over the net and the cord gets unplugged, thats an exception. Parsing data that is not correct, is not an exception. Lets say in this case, you want to parse -002 to -2, and the value begin parsed, turns out to be "-002$" then its not an exception, then the value ("you should know"), you want to parse is incorrect, handle it. thats to correct way, I believe. Furthermore, I believe the code engine will spin down for every exception it has to handle. Just a short comparison: for 1000 parsings Parse: 4078 milliseconds
                          Try Parse: 0 milliseconds

                          I used this code to test:

                                  Stopwatch sw = new Stopwatch();
                                  sw.Start();
                                  for (int i = 0; i < 1000; i++)
                                  {
                                      try { int demo = int.Parse("x"); }
                                      catch (Exception) {}
                                  }
                                  sw.Stop();
                                  Debug.WriteLine("Parse: " + sw.ElapsedMilliseconds);
                                  sw.Reset();
                                  sw.Start();
                                  for (int i = 0; i < 1000; i++)
                                  {
                                          int demo;
                                          int.TryParse("x", out demo);
                                  }
                                  sw.Stop();
                                  Debug.WriteLine("Try Parse: " + sw.ElapsedMilliseconds);
                          

                          With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                          P 3 Replies Last reply
                          0
                          • P Paw Jershauge

                            PIEBALDconsult wrote:

                            Only when it's available.

                            thats what i said ;) (if the method is there...) Now why would you even consider raising/throwing an exception, thats just bad pratice. never use exception for you code-flow. An exception should only be thrown, when it truly is an exception, like if your transfer data over the net and the cord gets unplugged, thats an exception. Parsing data that is not correct, is not an exception. Lets say in this case, you want to parse -002 to -2, and the value begin parsed, turns out to be "-002$" then its not an exception, then the value ("you should know"), you want to parse is incorrect, handle it. thats to correct way, I believe. Furthermore, I believe the code engine will spin down for every exception it has to handle. Just a short comparison: for 1000 parsings Parse: 4078 milliseconds
                            Try Parse: 0 milliseconds

                            I used this code to test:

                                    Stopwatch sw = new Stopwatch();
                                    sw.Start();
                                    for (int i = 0; i < 1000; i++)
                                    {
                                        try { int demo = int.Parse("x"); }
                                        catch (Exception) {}
                                    }
                                    sw.Stop();
                                    Debug.WriteLine("Parse: " + sw.ElapsedMilliseconds);
                                    sw.Reset();
                                    sw.Start();
                                    for (int i = 0; i < 1000; i++)
                                    {
                                            int demo;
                                            int.TryParse("x", out demo);
                                    }
                                    sw.Stop();
                                    Debug.WriteLine("Try Parse: " + sw.ElapsedMilliseconds);
                            

                            With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #13

                            Paw Jershauge wrote:

                            thats just bad pratice

                            Only at the application level, not at the framework level.

                            P 1 Reply Last reply
                            0
                            • P Paw Jershauge

                              PIEBALDconsult wrote:

                              Only when it's available.

                              thats what i said ;) (if the method is there...) Now why would you even consider raising/throwing an exception, thats just bad pratice. never use exception for you code-flow. An exception should only be thrown, when it truly is an exception, like if your transfer data over the net and the cord gets unplugged, thats an exception. Parsing data that is not correct, is not an exception. Lets say in this case, you want to parse -002 to -2, and the value begin parsed, turns out to be "-002$" then its not an exception, then the value ("you should know"), you want to parse is incorrect, handle it. thats to correct way, I believe. Furthermore, I believe the code engine will spin down for every exception it has to handle. Just a short comparison: for 1000 parsings Parse: 4078 milliseconds
                              Try Parse: 0 milliseconds

                              I used this code to test:

                                      Stopwatch sw = new Stopwatch();
                                      sw.Start();
                                      for (int i = 0; i < 1000; i++)
                                      {
                                          try { int demo = int.Parse("x"); }
                                          catch (Exception) {}
                                      }
                                      sw.Stop();
                                      Debug.WriteLine("Parse: " + sw.ElapsedMilliseconds);
                                      sw.Reset();
                                      sw.Start();
                                      for (int i = 0; i < 1000; i++)
                                      {
                                              int demo;
                                              int.TryParse("x", out demo);
                                      }
                                      sw.Stop();
                                      Debug.WriteLine("Try Parse: " + sw.ElapsedMilliseconds);
                              

                              With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #14

                              Paw Jershauge wrote:

                              Try Parse: 0 milliseconds

                              You don't find that a little suspicious? I expect the whole for loop got optimized away, I've had that happen before. Try summing up the values and print the sum after the loop to ensure that it doesn't it doesn't get optimized.

                              Paw Jershauge wrote:

                              catch (Exception) {}

                              I certainly didn't suggest that.

                              Paw Jershauge wrote:

                              int.Parse("x");

                              That's just silly.

                              P 1 Reply Last reply
                              0
                              • P Paw Jershauge

                                PIEBALDconsult wrote:

                                Only when it's available.

                                thats what i said ;) (if the method is there...) Now why would you even consider raising/throwing an exception, thats just bad pratice. never use exception for you code-flow. An exception should only be thrown, when it truly is an exception, like if your transfer data over the net and the cord gets unplugged, thats an exception. Parsing data that is not correct, is not an exception. Lets say in this case, you want to parse -002 to -2, and the value begin parsed, turns out to be "-002$" then its not an exception, then the value ("you should know"), you want to parse is incorrect, handle it. thats to correct way, I believe. Furthermore, I believe the code engine will spin down for every exception it has to handle. Just a short comparison: for 1000 parsings Parse: 4078 milliseconds
                                Try Parse: 0 milliseconds

                                I used this code to test:

                                        Stopwatch sw = new Stopwatch();
                                        sw.Start();
                                        for (int i = 0; i < 1000; i++)
                                        {
                                            try { int demo = int.Parse("x"); }
                                            catch (Exception) {}
                                        }
                                        sw.Stop();
                                        Debug.WriteLine("Parse: " + sw.ElapsedMilliseconds);
                                        sw.Reset();
                                        sw.Start();
                                        for (int i = 0; i < 1000; i++)
                                        {
                                                int demo;
                                                int.TryParse("x", out demo);
                                        }
                                        sw.Stop();
                                        Debug.WriteLine("Try Parse: " + sw.ElapsedMilliseconds);
                                

                                With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                P Offline
                                P Offline
                                PIEBALDconsult
                                wrote on last edited by
                                #15

                                Parse: 16016 500000000 Try Parse: 15440 500000000 About a four percent saving, big deal, it's not about performance anyway.

                                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch() ;

                                int demo = 0 ;

                                sw.Start() ;

                                for ( int i = 0 ; i < 100000000 ; i++ )
                                {
                                demo += int.Parse ( args [ 0 ] ) ;
                                }

                                sw.Stop() ;
                                System.Console.WriteLine ( "Parse: {0} {1}" , sw.ElapsedMilliseconds , demo ) ;

                                demo = 0 ;

                                sw.Reset() ;
                                sw.Start() ;

                                for ( int i = 0 ; i < 100000000 ; i++ )
                                {
                                int temp ;
                                int.TryParse ( args [ 0 ] , out temp ) ;
                                demo += temp ;
                                }

                                sw.Stop() ;
                                System.Console.WriteLine ( "Try Parse: {0} {1}" , sw.ElapsedMilliseconds , demo ) ;

                                P 1 Reply Last reply
                                0
                                • P PIEBALDconsult

                                  Paw Jershauge wrote:

                                  thats just bad pratice

                                  Only at the application level, not at the framework level.

                                  P Offline
                                  P Offline
                                  Paw Jershauge
                                  wrote on last edited by
                                  #16

                                  Also on framework level, Microsoft contradicts its self sometimes in the framework, but hey I dont always follow my own guidelines either. - If you know the Error, of why the code fails, handle it. - Only handle exceptions you can recover from. - If you dont know why the exception was thrown, its better to let the framework kill your app. According to microsoft. But then again others think you should clean up what you can, and then exiting the orderly fashion.

                                  With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                  P 1 Reply Last reply
                                  0
                                  • P PIEBALDconsult

                                    Paw Jershauge wrote:

                                    Try Parse: 0 milliseconds

                                    You don't find that a little suspicious? I expect the whole for loop got optimized away, I've had that happen before. Try summing up the values and print the sum after the loop to ensure that it doesn't it doesn't get optimized.

                                    Paw Jershauge wrote:

                                    catch (Exception) {}

                                    I certainly didn't suggest that.

                                    Paw Jershauge wrote:

                                    int.Parse("x");

                                    That's just silly.

                                    P Offline
                                    P Offline
                                    Paw Jershauge
                                    wrote on last edited by
                                    #17

                                    PIEBALDconsult wrote:

                                    You don't find that a little suspicious? I expect the whole for loop got optimized away, I've had that happen before. Try summing up the values and print the sum after the loop to ensure that it doesn't it doesn't get optimized.

                                    Actualy you might be right about the optimizing, but the fact is that the code is an will be faster running TryParse.

                                    PIEBALDconsult wrote:

                                    Paw Jershauge wrote: catch (Exception) {} I certainly didn't suggest that.

                                    i didn't say you did. this was only a very very short demo test.

                                    PIEBALDconsult wrote:

                                    Paw Jershauge wrote: int.Parse("x"); That's just silly.

                                    No not really, as my p.o.i. was to fail anyway.

                                            Stopwatch sw = new Stopwatch();
                                            int ParseOutPut = 0;
                                            sw.Start(); 
                                            for (int i = 0; i < 1000; i++) 
                                            { 
                                                try 
                                                { 
                                                    int demo = 0;
                                                    if(i % 3 == 0)
                                                        demo = int.Parse("x");
                                                    else
                                                        demo = int.Parse("1" + i.ToString());
                                                    ParseOutPut += demo;
                                                } 
                                                catch (Exception) { } 
                                            } 
                                            sw.Stop();
                                            Debug.WriteLine("Parse \[" + ParseOutPut + "\]: " + sw.ElapsedMilliseconds); 
                                            sw.Reset();
                                            int TryParseOutPut = 0;
                                            sw.Start(); 
                                            for (int i = 0; i < 1000; i++) 
                                            {
                                                int demo;
                                                if(i % 3 == 0)
                                                    int.TryParse("x", out demo);
                                                else
                                                    int.TryParse("1" + i.ToString(), out demo);
                                                TryParseOutPut += demo;
                                            } 
                                            sw.Stop();
                                            Debug.WriteLine("Try Parse \[" + TryParseOutPut + "\]: " + sw.ElapsedMilliseconds);
                                    

                                    Returns on my computer: Parse [938727]: 1464 ms Try Parse [938727]: 0 ms

                                    With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                    1 Reply Last reply
                                    0
                                    • P PIEBALDconsult

                                      Parse: 16016 500000000 Try Parse: 15440 500000000 About a four percent saving, big deal, it's not about performance anyway.

                                      System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch() ;

                                      int demo = 0 ;

                                      sw.Start() ;

                                      for ( int i = 0 ; i < 100000000 ; i++ )
                                      {
                                      demo += int.Parse ( args [ 0 ] ) ;
                                      }

                                      sw.Stop() ;
                                      System.Console.WriteLine ( "Parse: {0} {1}" , sw.ElapsedMilliseconds , demo ) ;

                                      demo = 0 ;

                                      sw.Reset() ;
                                      sw.Start() ;

                                      for ( int i = 0 ; i < 100000000 ; i++ )
                                      {
                                      int temp ;
                                      int.TryParse ( args [ 0 ] , out temp ) ;
                                      demo += temp ;
                                      }

                                      sw.Stop() ;
                                      System.Console.WriteLine ( "Try Parse: {0} {1}" , sw.ElapsedMilliseconds , demo ) ;

                                      P Offline
                                      P Offline
                                      Paw Jershauge
                                      wrote on last edited by
                                      #18

                                      Its all about performance, your code here assumes that everything is ok. so its not valid test.

                                      With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                      P 1 Reply Last reply
                                      0
                                      • P Paw Jershauge

                                        Its all about performance, your code here assumes that everything is ok. so its not valid test.

                                        With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                        P Offline
                                        P Offline
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #19

                                        If it fails, I want to throw and terminate.

                                        1 Reply Last reply
                                        0
                                        • P Paw Jershauge

                                          Also on framework level, Microsoft contradicts its self sometimes in the framework, but hey I dont always follow my own guidelines either. - If you know the Error, of why the code fails, handle it. - Only handle exceptions you can recover from. - If you dont know why the exception was thrown, its better to let the framework kill your app. According to microsoft. But then again others think you should clean up what you can, and then exiting the orderly fashion.

                                          With great code, comes great complexity, so keep it simple stupid...:-\ :-\

                                          P Offline
                                          P Offline
                                          PIEBALDconsult
                                          wrote on last edited by
                                          #20

                                          Paw Jershauge wrote:

                                          why the code fails, handle it.

                                          Some times you want to handle it by exiting.

                                          Paw Jershauge wrote:

                                          you can recover from

                                          Correct.

                                          Paw Jershauge wrote:

                                          its better to let the framework kill your app

                                          Yes, quite often, but that's up to the application, not any underlying code. But keep in mind that I write mostly console/batch programs and Windows Services.

                                          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