'printf' with leading zeros in C

CFormattingPrintf

C Problem Overview


I have a floating point number such as 4917.24. I'd like to print it to always have five characters before the decimal point, with leading zeros, and then three digits after the decimal place.

I tried printf("%05.3f", n) on the embedded system I'm using, but it prints *****. Do I have the format specifier correct?

C Solutions


Solution 1 - C

Your format specifier is incorrect. From the printf() man page on my machine:

>0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

>Field Width: >An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

>Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfred bassetView Question on Stackoverflow
Solution 1 - CCarl NorumView Answer on Stackoverflow