Aaron Yodaiken
Aaron Yodaiken

Reputation: 19561

Splitting a double into an array in C

I'd like the following code to work:

double num = 31415; /* num will never have a decimal part */
/* ... code here so that we can now say */
printf("%d", num_array[0] == 3 && num_array[1] == 1 && num_array[4] == 5); //1

I realize it's trivial to do this with ints (just int i=0; while(num>0) numarr[size-++i] = num%10, num/=10; where size is predetermined to be the number of digits in the number), but that obviously won't work for floats/doubles because you can't mod one floats.

And yes, I need to use floats/doubles, despite not using the floating point section (it's an exercise).

And I have figured out how to determine the number of digits in a double, using floor().

/* n > 0, n=floor(n) */
int numdigits(double n){
    int i = 0;
    while (n >0)
        n = floor(n/10), i++;
    return i;
}

Upvotes: 0

Views: 380

Answers (3)

Clifford
Clifford

Reputation: 93566

Apart from fmod(), you could also cast to a int64_t or long long int, and use % as before. If the range is less than 10 digits, you could use a int32_t.

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175705

It's probably easiest to just convert it to a string:

char* str = malloc(num_digits+1);
snprintf(str, num_digits+1, "%f", num);

Indexing into str will give you each digit as an ASCII value, so you'll need to subtract '0' to get the actual numeric value:

str[0] - '0' == 3;
str[1] - '0' == 1;
str[2] - '0' == 4;
...

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490663

Look up fmod. The number of digits will probably be easier to compute using log10.

Upvotes: 6

Related Questions