Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 284 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'printf' with leading zeros in C

#1
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?
Reply

#2
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through