Obtain the number of decimals of one decimal

Asked

Viewed 3,291 times

3

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

Ex.: If I receive the number:

4.5 - you must return 1
5.65 - you must return 2
6.997 - must return 3

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

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

And I’ve also seen that question of the Soen, but I would like to receive alternatives to these two forms.

2 answers

6


It has more "elegant" solutions using pure mathematics, but they would be much more complicated (someone might be tempted to do a simple operation and it won’t work for all situations). The simplest is this:

(3.1415.ToString(CultureInfo.InvariantCulture)).Split('.')[1].Length

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

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

  • I believe that the solution always involves transforming into strings, because floating point numbers cannot represent values like 0.2 or 0.1 exactly. If you use pure mathematics, you will find 15 decimal places because the value the computer sees is 0.1999999999999 or 0.1000000000000001. Rounding to a number of decimals less than 15 (according to what the application requires - could be 2, 5, 10...) and checking where zeroes start is an option.

  • Yeah, I actually have my doubts whether double it is possible to hit even with string. But the question was changed to decimal.

  • There is only one detail that needs to be corrected in this code, the way it is it is dependent on OS settings to work, exactly so it would give error in most computers in Brazilian Portuguese since they use by default the comma as decimal separator, but it is simple to correct by changing the ToString() for ToString(CultereInfo.InvariantCulture)

  • @Leandrogodoyrosa you’re right, edited, thank you.

1

If it’s just for different ways I’d like to use a while

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

https://dotnetfiddle.net/Zz5Wuu

Browser other questions tagged

You are not signed in. Login or sign up in order to post.