Get number of digits before decimal point
c#, decimal, numbers
Solution
Solution without converting to `string` (which can be dangerous in case of exotic cultures):
static int GetNumberOfDigits(decimal d)
{
decimal abs = Math.Abs(d);
return abs < 1 ? 0 : (int)(Math.Log10(decimal.ToDouble(abs)) + 1);
}
Note, that this solution is valid for all decimal values
UPDATE
In fact this solution does not work with some big values, for example: `999999999999998`, `999999999999999`, `9999999999999939`...
Obviously, the mathematical operations with `double` are not accurate enough for this task.
While searching wrong values I tend to use `string`-based alternatives proposed in this topic. As for me, that is the evidence that they are more reliable and easy-to-use (but be aware of cultures). Loop-based solutions can be faster though.
Thanks to commentators, shame on me, lesson to you.
Problem
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 return `3`.