I have a variable of decimal
type and I want to check the number of digits before decimal point in it.
What should I do? For example, 467.45
should
So, I've run into this before, and solved it with this code:
SqlDecimal d = new SqlDecimal(467.45M);
int digits = d.Precision - d.Scale;
SqlDecimal
is part of the System.Data.SqlTypes
namespace. "Precision" is the total number of significant digits, while "Scale" is the number of digits after the decimal point.
Now, I know one objection to going this route is that SqlDecimal
is part of the SQL Server-specific code. It's a valid point, but I would also point out that it's a part of the .NET framework itself, and has been since at least version 1.1, so it seems like it would be still be applicable no matter what the code around it is doing.
I looked under the hood with a decompiler (JetBrains' dotPeek in this instance), to see if maybe the code for calculating precision and scale could be easily extracted and just used, without pulling in SqlDecimal
. The code to calculate scale is very simple, but the method to calculate precision is non-trivial, so if it were me, I'd just go through SqlDecimal
.