如何在C#中去掉负数的前导零?
例如,我希望‘-01’转换为‘-1’。
例如,我希望‘-01’转换为‘-1’。
Int32.Parse()
或 Convert.ToInt32()
,应该可以处理前导零:Convert.ToInt32("-01"); // yields -1
幕后花絮
如果你深入这些方法的实现细节, 你会发现这调用了底层的StringToNumber()
方法和随后的ParseNumber()
方法,它们应该处理前导和尾随零:
// 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;
}
string
:var negativeStrNum = "-000005";
Console.WriteLine(int.Parse(negativeStrNum));
这会给你-5
那 int.Parse("-01").ToString()
怎么样?
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);
"
来表示字符串。由于您正在谈论数字,因此您确实需要更清楚地了解字符、字符串或数字。您正在从什么转换,以及您要转换成什么?投票关闭。 - Jonathan Wood