tags:

views:

61

answers:

2

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?

Cheers

+1  A: 

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
+5  A: 

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
1+. Just about to say that.
Aliostad