user4881284
user4881284

Reputation:

storing a double in a char string.C

am trying to store a double between 0-100 in a char array.

here is what am doing

else if (average >= 10){
        scores[45] = (average / 10.0) + '0';
        scores[46] = ((int)average % 10) + '0';
        scores[47] = '.';
        scores[48] =  ((average / 10 - (((int)average) / 10)) * 10)+ '0';
        scores[49] = ((int)((average / 10 - ((int)average / 10)) * 100)) % 10 + '0';

    }
    else {
        scores[46] = ((int)average % 10) + '0';
        scores[47] = '.';
        scores[48] = ((average / 10 - (((int)average) / 10)) * 10) + '0';
        scores[49] = ((average / 10 - ((int)average / 10)) * 100)) % 10 + '0';
    }


}

everything works except the first number after the . I get 6.60 when the average is supposed to be 6.00. how do I fix this?

by the way am only storing the integer part and 2 numbers after the decimal point as you see. that's all I need

Upvotes: 0

Views: 311

Answers (2)

Ed Heal
Ed Heal

Reputation: 60017

Just use snprintf. No hassle job done

Upvotes: 0

M Oehm
M Oehm

Reputation: 29126

Your expressions are needlessly complicated, because you end up casting and dividing the some stuff over and over.

I'd determine the integer representation of my whole and fractional parts first and then print the ith digit as:

digit = '0' + value / pow10(i) % 10

Of course, you have two-digit values, so that simplifies to

hi = '0' + val / 10
lo = '0' + val % 10

For your example:

int ival = average * 100 + 0.5;
int iint = ival / 100;
int ifrac = ival % 100;

scores[45] = (iint >= 10) ? '0' +  iint / 10 : ' ';
scores[46] = '0' + iint % 10;
scores[47] = '.';
scores[48] = '0' + ifrac / 10;
scores[49] = '0' + ifrac % 10;

The ' + 0.5' is for rounding the number when converting it to an integer.

As Joachim Pileborg points out, there is already a workable solution for your problem: Just use

snprintf(scores + 45, 6, "%5.2f", average);

Upvotes: 1

Related Questions