Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'printf' with leading zeros in C

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?

like image 662
fred basset Avatar asked Feb 15 '11 17:02

fred basset


People also ask

What is leading zeros in C?

If the position of zero before bit is set to one, they are termed as leading zeros.

How do you print numbers with leading zeros?

Use the str. zfill() Function to Display a Number With Leading Zeros in Python. The str. zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes.

What is %f %s in C?

%f. a floating point number for floats. %u. int unsigned decimal. %e.

How can I add zeros in front of a number in C?

and I do this: //pass in value of seconds hr = sec/3600; t = sec%3600; min= t/60; sec = t%60; char *colon = ":"; printf("%llu%s%llu%s%llu\t", hr,colon,min,colon,sec);


1 Answers

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.

like image 185
Carl Norum Avatar answered Sep 19 '22 18:09

Carl Norum