A solution without conversion to string (which can be dangerous in the case of exotic crops):
static int GetNumberOfDigits(decimal d) { decimal abs = Math.Abs(d); return abs < 1 ? 0 : (int)(Math.Log10(decimal.ToDouble(abs)) + 1); }
Please note that this solution is valid for all decimal values.
UPDATE
In fact, this solution does not work with some large values, for example: 999999999999998 , 999999999999999 , 9999999999999939 ...
Obviously, the mathematical operations with double not accurate enough for this task.
When looking for incorrect values, I tend to use string based alternatives suggested in this section. As for me, this indicates that they are more reliable and easier to use (but keep in mind the cultures). Loop-based solutions can be faster though.
Thanks to the commentators, ashamed of me, a lesson for you.
astef Feb 04 '14 at 7:59 2014-02-04 07:59
source share