Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

padding doubles with 0 1

Status
Not open for further replies.

neonep

Programmer
Jun 26, 2003
34
int num = 32;

fprintf ( file, "%6d", num ); writes " 32" into the file
fprintf ( file, "%06d", num ); writes "000032" into the file

How can I use similar padding to put 0's before digits of a double?

So if I have
double d = 32.5;

fprintf ( file, "%4.2f", d ); yields " 32.5"

I want it to be "0032.5"

Any help will be appreciated. Thanks.
 
Code:
#include <stdio.h>

int main(void)
{
   double d = 32.5;
   printf ( "%[red]06.1[/red]f\n", d );
   return 0;
}

/* my output
0032.5
*/
The 6 is the total width (which includes the decimal point and fractional digits).
 
This is the best I can come up with. Maybe someone can do something better
Code:
#include <stdio.h>
#include <string.h>
int main ()
{
   float x = 32.5;
   char str[32];

   sprintf (str, "0000%.2f", x);
   printf ("%s\n", &str[strlen(str) - 7]);
   return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top