C formatted string - How to add leading zeros to float and int values?
Solution 1
You can zero pad with %08.4f
, for example. Note that the first number is the entire field width, not just the number of places you want before the decimal. In your example, the 3
in %3.4
has no effect. If you want your last number to only have three decimal places, you'll want %07.3f
for that one.
The %d
formats are easier - in your case, just %02d
should do it.
Solution 2
Below formatting will help you.
float a = 1;
int x = 1, y = 2;
printf("06 BR%02d%02d %08.4f %08.4f %08.4f\n", x, y, a, a, a);
output for me is
06 BR0102 001.0000 001.0000 001.0000
Admin
Updated on June 30, 2022Comments
-
Admin almost 2 years
Possible Duplicate:
Extra leading zeros when printing float using printf?I'm trying to get the output of this C program to have placeholder zeros, as the output of this program will be used as input for another program. Right now, I'm using the following print line.
fprintf(fp1, "06 BR%d%d %3.4f%3.4f%3.4f\n",i,d,X,Y,Z); i = index for the loop d = index for a second loop X = double for a Cartesian system Y = double for a Cartesian system Z = double for a Cartesian system
Right now the output looks like this:
06 BR12 1.00001.00001.0000
I want it to be like the following:
06 BR0102 001.0000001.0000001.000
I know that I could just add placeholding zeros manually (if i<10, add a placeholder, etc.) but is there a more efficient way to output a placeholder zero than simply adding them in if-statements?
Thank you in advance.
-
gsamaras over 5 yearsExplaining it a bit would be nice.