Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

double

digits

I have a double which is not necessarily positive but usually. It can be 0.xxxx000 or X.xxxx00000 or XX.00000 or 0.xxx0xxx00000, where eventually there are all 0's to the right of the last number. I need to keep track of how many digits there are. I've been having trouble with this, any help? This is C.

like image 552
cdietschrun Avatar asked Dec 13 '22 14:12

cdietschrun


2 Answers

A double has 52 mantissa bits plus an implicit "1" bit, so you should be able to type-pun a double pointer to a 64-bit integer (getting the raw bits into an integer), &= this with (1<<52)-1, and |= the result with (1<<52).

The log10 of that would be the number of decimal digits.

Though, I'm almost inclined to say "go with jonsca's solution" because it is so ingeniously simple (it deserves a +1 in any case for being KISS).

like image 190
Damon Avatar answered Jan 04 '23 23:01

Damon


Use sprintf to turn it into a string and do whatever counting/testing you need to do on the digits

like image 42
jonsca Avatar answered Jan 05 '23 00:01

jonsca