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
.
Use TRUNC(158.96) to get the digits before decimal point.
The number before the decimal point is called the whole part or integral part, Whereas the number after the decimal point is called the fractional part. Example : 43 is a whole part and 012 is a fractional part.
Count and identify the decimal place of a number In a blank cell, saying the Cell B2, enter the formula of =IF(A2=INT(A2),0,LEN(MID(A2-INT(A2),FIND(".",A2,1),LEN(A2)-FIND(".",A2,1)))), and press the Enter key. Then it returns the decimal place in the Cell B2. In this case, it shows 5.
The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With