Get number of digits before decimal point

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

    The mathematical way of doing this (and probably the fastest) is to get a logarytm of base 10 of a absolute value of this number and round it up.

    Math.Floor(Math.Log10(Math.Abs(val)) + 1);
    
    0 讨论(0)
  • 2020-12-28 12:08

    Use modulo, i'm not a C# programmer, but I'm pretty sure this solution work:

    double i = 1;
    int numberOfDecimals = 0;
    
    
    while (varDouble % i != varDouble)
    {
    numberOfDecimals++;
    i*=10;
    }
    
    return numberOfDecimals;
    
    0 讨论(0)
  • 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 :).

    0 讨论(0)
  • 2020-12-28 12:11

    You could use ToString function with a custom format.

    Decimal value = 467.45m;
    int count = Math.Abs(value).ToString("#", System.Globalization.CultureInfo.InvariantCulture).Length;
    

    The # specify you only want the characters before the .

    The System.Globalization.CultureInfo.InvariantCulture ensure you won't get any formating from the Region Option.

    0 讨论(0)
  • 2020-12-28 12:12

    I would prefer the following instead of casting to int to ensure that you can also handle big numbers (e.g. decimal.MaxValue):

    Math.Truncate ( Math.Abs ( decValue ) ).ToString( "####" ).Length
    
    0 讨论(0)
  • 2020-12-28 12:12

    simple :

    string value = "467.45";
    int count =  value.split('.')[0] == "0" ? 0 : value.split('.')[0].ToString().Replace("-","").Count();
    
    0 讨论(0)
提交回复
热议问题