How can I remove leading zeroes on negative numbers in C#?
For example, I wish '-01' to convert to '-1'.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With