Get the number of decimal places of a decimal


How can I get the number of decimal places of a decimal variable?

Eg: If I receive the number:


4.5 - should return 1
  5.65 - should return 2
  6.997 - should return 3

I know you can do this by converting to string , something like:

decimal CasasDecimais(decimal arg){
     return arg.ToString().Substring(arg.ToString().LastIndexOf(",") + 1).Length;

And I've also seen this question of SOen, but I would welcome alternatives to these two forms.

asked by anonymous 05.10.2015 / 19:49

2 answers


It has more "elegant" solutions using pure mathematics, but would be much more complicated (one may be tempted to do a simple operation and will not work for all situations). The simplest is this:


See running on dotNetFiddle .


Then there was an edit but for decimal the algorithm is the same.

05.10.2015 / 20:08

If it is only in different ways, you would have to use a while

public static int casasDecimais(decimal d)
    int res = 0;
    while(d != (long)d)
        d = d*10;
    return res;


05.10.2015 / 21:20