How could I convert data from string to long in c#

前端 未结 9 2312
慢半拍i
慢半拍i 2021-02-02 04:45

How could i convert data from string to long in C#?

I have data

String strValue[i] =\"1100.25\";

now i want it in

long         


        
9条回答
  •  太阳男子
    2021-02-02 05:14

    You can create your own conversion function:

        static long ToLong(string lNumber)
        {
            if (string.IsNullOrEmpty(lNumber))
                throw new Exception("Not a number!");
            char[] chars = lNumber.ToCharArray();
            long result = 0;
            bool isNegative = lNumber[0] == '-';
            if (isNegative && lNumber.Length == 1)
                throw new Exception("- Is not a number!");
    
            for (int i = (isNegative ? 1:0); i < lNumber.Length; i++)
            {
                if (!Char.IsDigit(chars[i]))
                {
                    if (chars[i] == '.' && i < lNumber.Length - 1 && Char.IsDigit(chars[i+1]))
                    {
                        var firstDigit = chars[i + 1] - 48;
                        return (isNegative ? -1L:1L) * (result + ((firstDigit < 5) ? 0L : 1L));    
                    }
                    throw new InvalidCastException($" {lNumber} is not a valid number!");
                }
                result = result * 10 + ((long)chars[i] - 48L);
            }
            return (isNegative ? -1L:1L) * result;
        }
    

    It can be improved further:

    • performance wise
    • make the validation stricter in the sense that it currently doesn't care if characters after first decimal aren't digits
    • specify rounding behavior as parameter for conversion function. it currently does rounding

提交回复
热议问题