Conting the number of decimals (variant of the Math.Round utility)?

I would like to count the number of decimals (i.e. number of digits below the fractional comma/point) in a double value. I can think of many (dirty & not culture safe) ways of doing this, but I am looking for a reliable solution.

Does anyone has a solution to this problem

Thanks in advance,
Joannes


Answer this question

Conting the number of decimals (variant of the Math.Round utility)?

  • jazg

    I'm the development owner of Double. Since Double is internally base 2 rather than base 10, any attempt to count the decimals will be imprecise, so the techniques in the previous post are about your best option. However, this won't work reliabily for more than about 12 digits. If accuracy matter, I recommend using the Decimal type instead.

  • Danny Tsai

    Hi!

    You have at least two choices:

    1. format to string using current culture and count characters after separator (a little weird, but easy to implement and understand culture settings)

    2. do something like that pseudocode:

    double current = your_value - Math.Floor(your_value);

    int count = 0;

    while(current != 0)

    {

    count++;

    current *= 10;

    current = current - Math.Floor(current);

    }



  • Conting the number of decimals (variant of the Math.Round utility)?