5

How can I remove leading zeroes on negative numbers in C#?

For example, I wish '-01' to convert to '-1'.

d219
  • 2,707
  • 5
  • 31
  • 36
Taewan
  • 1,167
  • 4
  • 15
  • 25
  • 1
    In C# the `'` character is used to enclose characters. You need to use `"` for strings. And since you are talking about numbers, you really need to be more clear regarding characters, strings or numbers. What are you converting from, and what are you converting to? Voting to close. – Jonathan Wood May 11 '16 at 17:21
  • if you specify an INPUT TYPE and an OUTPUT TYPE, we could build a nice function, and i'm sure you can do it too – Antoine Pelletier May 11 '16 at 17:26

4 Answers4

3

Assuming that your input will be an actual string, then you can use any of the common integer parsing methods like Int32.Parse() or Convert.ToInt32() should handle leading zeros :

Convert.ToInt32("-01"); // yields -1

Behind the Scenes

If you dig into the implementation of these methods, you'll see that this calls an underlying StringToNumber() method and subsequent ParseNumber() method that should take care of handling leading and trailing zeros :

// This is called via the following methods
// 1.) Convert.ToInt32()
// 2.) Int32.Parse()
// 3.) Number.ParseInt32()
// 4.) StringToNumber() (this method)
// 5.) ParseNumber() (called by this method)
[System.Security.SecuritySafeCritical]  // auto-generated
private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal) {

        if (str == null) {
            throw new ArgumentNullException("String");
        }
        Contract.EndContractBlock();
        Contract.Assert(info != null, "");
        fixed (char* stringPointer = str) {
            char * p = stringPointer;
            if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal) 
                || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) {
                throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
            }
        }
}

private static Boolean TrailingZeros(String s, Int32 index) {
        // For compatability, we need to allow trailing zeros at the end of a number string
        for (int i = index; i < s.Length; i++) {
            if (s[i] != '\0') {
                return false;
            }
        }
        return true;
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
1

You could try parsing the string:

var negativeStrNum = "-000005";

Console.WriteLine(int.Parse(negativeStrNum));

That gives you -5

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
0

How about int.Parse("-01").ToString() ?

Stefan Schmiedl
  • 505
  • 5
  • 21
0
        string InputString = "-020.50";
        for (int i = 0; i < InputString.Length; i++)
        {
            char CurrentCharacter = InputString[i];

            if (Char.IsDigit(CurrentCharacter))
            {
                if (CurrentCharacter == '0')
                {
                    InputString = InputString.Remove(i, 1);
                    i--;
                }
                else
                    break;
            }
        }
        Console.WriteLine(InputString);
Stack
  • 348
  • 3
  • 17