Get number of digits before decimal point

前端 未结 25 1942
独厮守ぢ
独厮守ぢ 2020-12-28 11:53

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should

25条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 11:53

    decimal d = 467.45M;
    int i = (int)d;
    Console.WriteLine(i.ToString(CultureInfo.InvariantCulture).Length); //3
    

    As a method;

    public static int GetDigitsLength(decimal d)
    {
      int i = int(d);
      return i.ToString(CultureInfo.InvariantCulture).Length;
    }
    

    Note: Of course you should check first your decimals full part is bigger than Int32.MaxValue or not. Because if it is, you get an OverflowException.

    Is such a case, using long instead of int can a better approach. However even a long (System.Int64) is not big enough to hold every possible decimal value.

    As Rawling mentioned, your full part can hold the thousands separator and my code will be broken in such a case. Because in this way, it totally ignores my number contains NumberFormatInfo.NumberGroupSeparator or not.

    That's why getting numbers only is a better approach. Like;

    i.ToString().Where(c => Char.IsDigit(c)).ToArray()
    

提交回复
热议问题