Get number of digits before decimal point

前端 未结 25 1932
独厮守ぢ
独厮守ぢ 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 12:13

    Algorithm:

    • Convert |decimal| to String.
    • If "." exist in the decimal, cut before it, otherwise consider the whole number.
    • Return string length.

    Example:

    3.14 --> 3.14 --> "3.14" --> "3.14".Substring(0,1) --> "3".Length --> 1
    
    -1024 --> 1024 --> "1024" --> IndexOf(".") = -1 --> "1024" --> 4
    

    Code:

    static int getNumOfDigits (decimal num)
    {
        string d = Math.Abs(num).ToString();
    
        if (d.IndexOf(".") > -1)
        {
            d = d.Substring(0, d.IndexOf("."));
        }
    
        return d.Length;
    }
    

提交回复
热议问题