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?
If the position of zero before bit is set to one, they are termed as 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.
%f. a floating point number for floats. %u. int unsigned decimal. %e.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With