sprintf()
does not provide a "significant figures before".
It does provide a minimum field width which can be derived from sig_figs_before
, sig_figs_after
and the value itself.
char * Send_Data(float Data[10], const char* SUBJECT_SEND_NAME,
char *Data_Backup, int sig_figs_before, int sig_figs_after) {
assert(sig_figs_before >= 1);
assert(sig_figs_after >= 0);
float Data_Ave = ((Data[0] + Data[1] + Data[2] + Data[3] + Data[4] +
Data[5] + Data[6] + Data[7] + Data[8] + Data[9])/10);
int width = sig_figs_before + 1 + sig_figs_after; // +1 for '.'
// Make room for '-'
if (Data_Ave < 0) width++;
sprintf(msgBody, "%#*.*f, ", width, sig_figs_after, Data_Ave);
}
'#'
is used should sig_figs_after == 0
to preserve the decimal point.
Note: this does not limit the width or the number of sig_figs_before
should Data_Ave
be large. @Matt Patenaude idea to use snprintf()
is a good one.
A hack approach would be to test:
if (log10(fabs(Data_Ave)+0.5) > sig_figs_before) UseAlternativePrint();