Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of digits before decimal point

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.

like image 391
fasadat Avatar asked Feb 04 '14 07:02

fasadat


People also ask

How do you find the number before the decimal point?

Use TRUNC(158.96) to get the digits before decimal point.

What are the digits before the decimal point called?

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.

How do I count numbers before decimal in Excel?

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.

How do you find the number of digits after a decimal point?

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.


1 Answers

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.

like image 65
astef Avatar answered Sep 19 '22 17:09

astef