Find number of decimal places in decimal value regardless of culture

Jesse Carter picture Jesse Carter · Nov 20, 2012 · Viewed 100.3k times · Source

I'm wondering if there is a concise and accurate way to pull out the number of decimal places in a decimal value (as an int) that will be safe to use across different culture info?

For example:
19.0 should return 1,
27.5999 should return 4,
19.12 should return 2,
etc.

I wrote a query that did a string split on a period to find decimal places:

int priceDecimalPlaces = price.ToString().Split('.').Count() > 1 
                  ? price.ToString().Split('.').ToList().ElementAt(1).Length 
                  : 0;

But it occurs to me that this will only work in regions that use the '.' as a decimal separator and is therefore very brittle across different systems.

Answer

burning_LEGION picture burning_LEGION · Nov 21, 2012

I used Joe's way to solve this issue :)

decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];