-1

If I have a number, how can I determine the number of decimals?

e.g. for 0.0001 I want to get the result 4

The duplicate suggested above is less suitable than this one because they are taking about culture-independent code but this question is just about decimal oriented code (i.e. after the decimal). So no need to introduce any more overhead:

Finding the number of places after the decimal point of a Double

but they both are good threads.

Community
  • 1
  • 1
ycomp
  • 8,316
  • 19
  • 57
  • 95
  • Possible duplicate: http://stackoverflow.com/questions/9386672/finding-the-number-of-places-after-the-decimal-point-of-a-double – Jite Nov 21 '14 at 08:09
  • thats how you do it http://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture – Vajura Nov 21 '14 at 08:09
  • I believe this will be enough: Math.Abs(Math.Floor(Math.Log10(d))) – Konrad Kokosa Nov 21 '14 at 08:12
  • I ended up using d.ToString("R").Split('.')[1].Length; from one of the links above. Seems to work and is nice and compact. Maybe not the most efficient way since strings are involved but that doesn't matter for my project. – ycomp Nov 21 '14 at 10:39

1 Answers1

2

You can't really. A double is a floating point precision data type, so it's never precise.

You could hack something around, using ToString:

double d = 0.994562d;

int numberOfDecimals = d.ToString(CultureInfo.InvariantCulture).Length
                       - d.ToString(CultureInfo.InvariantCulture).IndexOf('.')
                       - 1
                       ;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325