Hi I want to format float numbers such that it will be displayed as follows:
decimal.fraction
where decimal = max 11 digits and fraction = max 9 digits
and if no fraction part it should display not fraction and for more than 11 digits in decimal p开发者_如何学运维art representation will be in scientific form.
Can anyone help me ?
I don't think there's an internal format like this. 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);
}
}
The standard library cannot directly do that for you. I would suggest your own decimal formatter if you need that specialized formatting, but you can also do by measuring the value and then setting proper mode and precision for the standard library.
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;
}
I think streams 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();
精彩评论