Get number of digits before decimal point

前端 未结 25 1933
独厮守ぢ
独厮守ぢ 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:08

    Here is my optimized version of the code inspired by Gray's answer:

        static int GetNumOfDigits(decimal dTest)
        {
            int nAnswer = 0;
    
            dTest = Math.Abs(dTest);
    
            //For loop version
            for (nAnswer = 0; nAnswer < 29 && dTest > 1; ++nAnswer)
            {
                dTest *= 0.1M;
            }
    
            //While loop version
            //while (dTest > 1)
            //{
            //    nAnswer++;
            //    dTest *= 0.1M;
            //}
    
            return (nAnswer);
        }
    

    If you don't want the Math.Abs to be called inside this function then be sure to use it outside the function on the parameter before calling GetNumOfDigits.

    I decided to remove the other codes to reduce clutter in my answer, even though they helped me get to this point...

    If there is any improvements needed, then let me know and I will update it :).

提交回复
热议问题