MammothOne - 2 months ago 30

C# Question

How to count precision digits on a C# decimal type?

e.g. 12.001 = 3 precision digits.

I would like to thrown an error is a precision of greater than x is present.

Thanks.

Answer

You can get the "scale" of a `decimal`

like this:

```
static byte GetScale(decimal d)
{
return BitConverter.GetBytes(decimal.GetBits(d)[3])[2];
}
```

Explanation: `decimal.GetBits`

returns an array of four `int`

values of which we take only the last one. As described on the linked page, we need only the second to last `byte`

from the four bytes that make up this `int`

, and we do that with `BitConverter.GetBytes`

.

Examples: The scale of the number `3.14m`

is `2`

. The scale of `3.14000m`

is `5`

. The scale of `123456m`

is `0`

. The scale of `123456.0m`

is `1`

.