Given double, you need to find how many digits in total

I have a double that is not necessarily positive, but usually. It can be 0.xxxx000 or X.xxxx00000 or XX.00000 or 0.xxx0xxx00000, where ultimately all 0 is to the right of the last number. I need to keep track of how many digits there are. I had problems with this, any help? This is C.

+4
source share
3 answers

Use sprintf to turn it into a string, and do any calculations / testing needed for numbers

+5
source

The double has a 52 mantissa bit plus the implicit bit β€œ1”, so you should be able to type a double pointer to a 64-bit integer (getting the original bits into an integer), & = this with (1 <52) -1, and | = result with (1 <52).

In this case, log10 will be the number of decimal digits.

Although, I am almost inclined to say "go with a solution for jonsca" because it is so inventively simple (it deserves +1 anyway for KISS).

+5
source

The double representation is not decimal - it is binary (like all other numbers on the computer). The task you defined does not make much sense. Consider an example: the number 1.2 is converted to binary - 1 + 1/5 = 1. (0011) binary [0011 in period]. If you cut it to 52 bits of precision (double), you get the binary code 1.0011001100110011001100110011001100110011001100110011, equal to 1+ (1-1 / 2 ^ 52) / 5. If you represent this number in decimal form, you will get 52 decimal places to all zeros, which is much more than the maximum decimal precision of the double, which is 16 digits (and all these digits represent from 17 to 52 are simply meaningless).

In any case, if you have a purely abstract problem (for example, at school):

int f( double x ) { int n = 0; x = fabs(x); x -= floor(x); while( x != floor(x) ) { x *= 2; ++n; } return n; } 

The function returns the number of binary digits before all zeros, as well as the number of decimal digits before all zeros (the last decimal digit is always 5 if the return value is> 0).

+2
source

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


All Articles