How can you get the first digit in an int (C#)?

后端 未结 25 2791
遇见更好的自我
遇见更好的自我 2020-12-02 05:43

In C#, what\'s the best way to get the 1st digit in an int? The method I came up with is to turn the int into a string, find the 1st char of the string, then turn it back to

25条回答
  •  既然无缘
    2020-12-02 05:58

    Check this one too:

    int get1digit(Int64 myVal)
    {
        string q12 = myVal.ToString()[0].ToString();
        int i = int.Parse(q12);
        return i;
    }
    

    Also good if you want multiple numbers:

    int get3digit(Int64 myVal) //Int64 or whatever numerical data you have
    {
        char mg1 = myVal.ToString()[0];
        char mg2 = myVal.ToString()[1];
        char mg3 = myVal.ToString()[2];
        char[] chars = { mg1, mg2, mg3 };
        string q12= new string(chars);
        int i = int.Parse(q12);
        return i;
    }
    

提交回复
热议问题