4

I'm trying to get the number of digits in the following double value: 56.46855976 without using converting it to a string (and simply replacing the "." with a "").

Anybody got any ideas?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Simian
  • 801
  • 1
  • 12
  • 20
  • Aww shucks, what is wrong with: `double d = 56.46855976; int length = d.ToString().Replace(".", "").Length;` – slugster Sep 16 '10 at 11:50
  • 4
    Take into account also that the number you see (56.46855976) is only a *representation* of a value. The value 1/3 is very short, the number 0.33333... isn't. So except for view issues there is not much information in the length of a number. – Martin Hennings Sep 16 '10 at 11:54
  • Possible duplicate of [c# Decimal to string for currency](https://stackoverflow.com/questions/10437416/c-sharp-decimal-to-string-for-currency) – TylerH Feb 16 '18 at 16:59

3 Answers3

5

Count how often you must divide the number by 10 until it's smaller than 1 -> that gives you the digits before the decimal point.

Then count how often you must multiply the original number by 10 until it equals the Math.Floor-result -> that gives you the digits behind the decimal points.

Add. Be glad.

Edit: As Joey points out, there is some uncertianity in it. Define a maximum number of digits beforehand so you don't create an infinite loop. On the other hand - "How long is the coast of Denmark?"...

Martin Hennings
  • 16,418
  • 9
  • 48
  • 68
1
    /// Returns how many digits there are to the left of the .
    public static int CountDigits(double num) {
        int digits = 0;
        while (num >= 1) {
            digits++;
            num /= 10;
        }
        return digits;
    }

As Martin mentioned, counting to the right of the . is pointless.

Tests:

MathPlus.CountDigits(56.46855976)                 -> 2
MathPlus.CountDigits((double)long.MaxValue + 1)   -> 19
MathPlus.CountDigits(double.MaxValue)             -> 309
Petrucio
  • 5,491
  • 1
  • 34
  • 33
0

Converting to a string might be the best option you have. Remember that doubles are represented in Base 2 internally. Therefore the decimal representation you see is only an approximation of the actually stored value (except for integers up to 253) which is a sum of individual powers of 2.

So trying to figure out the number of decimal digits from the binary representation is certainly not an easy or trivial task – especially since the framework might also apply rounding to make numbers like 3.999999999998 appear like 4.0 since they appear to have more precision than there actually is.

Joey
  • 344,408
  • 85
  • 689
  • 683