Finding the string length of a integer in .NET

后端 未结 6 616
小鲜肉
小鲜肉 2020-12-28 18:12

In .NET what is the best way to find the length of an integer in characters if it was represented as a string?

e.g.

1 = 1 character
10 = 2 characters

6条回答
  •  温柔的废话
    2020-12-28 18:22

    If you need to deal with negative numbers also, you can take stmax solution with a spin:

    public static int IntLength(int i) { 
      if (i == 0) return 1; // no log10(0)
      int n = (i < 0) ? 2 : 1;
      i = (i < 0) ? -i : i;
    
      return (int)Math.Floor(Math.Log10(i)) + n; 
    } 
    

提交回复
热议问题