Floating-point format

Hi, I want to format floating point numbers so that they display as follows:

decimal.fraction

where decimal = max 11 digits and fraction = max 9 digits

and if the partial part should not be displayed not in fractions and more than 11 digits in decimal part, then it will be in scientific form.

Can anybody help me?

+4
source share
4 answers

I don’t think there is such an internal format. You need to format it yourself (not tested):

void fprintf_float(FILE* f, double value) { if (-1e11 < value && value < 1e11) { double d = fabs(value); const char* sign = d > 0 ? "" : "-"; double ipart, fpart; char fpartstr[16]; int pos; fpart = modf(d, &ipart); snprintf(fpartstr, 16, "%.9f", fpart); for (pos = 10 /*strlen(fpartstr)-1*/; pos > 0; -- pos) if (fpartstr[pos] != '0' && fpartstr[pos] != '.') break; fpartstr[pos+1] = '\0'; fprintf(f, "%s%.11g%s", sign, ipart, fpartstr+1); } else { fprintf(f, "%.10e", value); } } 
+3
source

The standard library cannot directly do this for you. I would suggest your own decimal formatter if you need this specialized formatting, but you can also do this by measuring the value and then setting the correct mode and accuracy for the standard library.

+1
source

Like this?

 #include <stdio.h> #include <string.h> #include <math.h> void printnum(double num_in) { char buff[32]; char buff2[32]; if (num_in >= 10000000000.0) { sprintf (buff, "%e", num_in); } else { char *pt; unsigned long long tmp; tmp = floor (num_in); sprintf (buff, "%llu", tmp); num_in -= tmp; if(num_in < 1.0e-11) { printf("%s\n",buff); return; } sprintf (buff2, "%10.9lf", num_in); pt = memchr (buff2, '.', 32); strcat (buff, pt); } printf("%s\n",buff); } int main(void) { double t = 100.0; int i; for(i=0;i<11;i++) { printf("%lf\t",t); printnum(t); t *= 12.3456; } return 0; } 
0
source

I think threads can do the job.

 #include <locale> #include <sstream> std::wostringstream out; out.imbue(std::locale::classic()); // Make sure a '.' is used as decimal point out.precision(9); // set fraction to 9 digits out << 1.2; const std::wstring str = out.str(); 
0
source

Source: https://habr.com/ru/post/1303088/


All Articles