如何在C#中删除负数上的引号零?
例如,我希望'-01'转换为'-1'。
答案 0 :(得分:3)
假设您的输入是实际字符串,那么您可以使用任何常见的整数解析方法,如Int32.Parse()
或Convert.ToInt32()
应该处理前导零:
Convert.ToInt32("-01"); // yields -1
幕后花絮
如果你挖掘into the implementation of these methods,你会发现这会调用一个基础的StringToNumber()
方法和随后的ParseNumber()
method,它应该处理前导零和尾随零:
// 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;
}
答案 1 :(得分:1)
您可以尝试解析string
:
var negativeStrNum = "-000005";
Console.WriteLine(int.Parse(negativeStrNum));
这会给你-5
答案 2 :(得分:0)
int.Parse("-01").ToString()
怎么样?
答案 3 :(得分: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);