How can you get the number of digits contained in a double?

风格不统一 提交于 2019-12-06 01:19:07

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?"...

    /// 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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!