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

I am trying to get the number of digits in the following double value: 56.46855976 without using converting it to a string (and just replacing "." With "").

Does anyone have any ideas?

+3
source share
3 answers

Indicate how often you should divide the number by 10 until it becomes less than 1 →, which will give you digits up to a decimal point.

Then count how often you have to multiply the original number by 10 until it becomes Math.Floor-result →, which gives you the numbers after the decimal point.

Add. Be glad.

. , . , . - " ?"...

+5
    /// 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;
    }

, . .

:

MathPlus.CountDigits(56.46855976)                 -> 2
MathPlus.CountDigits((double)long.MaxValue + 1)   -> 19
MathPlus.CountDigits(double.MaxValue)             -> 309
+1

. , double 2. , , ( 2 53), 2.

Thus, trying to determine the number of decimal digits from a binary representation is certainly not a simple or trivial task - especially since the framework can also apply rounding so that numbers like 3.999999999998 look like 4.0, since they seem to have more precision than it actually is.

0
source

Source: https://habr.com/ru/post/1765087/


All Articles