我有一个 float ,例如 4917.24
。我想把它打印成小数点前总是有五个字符,前导零,然后是小数点后三个数字。
我在我正在使用的嵌入式系统上尝试了 printf("%05.3f", n)
,但它打印了 *****
。我的格式说明符是否正确?
最佳答案
您的格式说明符不正确。从我机器上的 printf()
手册页:
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;
对于您的情况,您的格式为 %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
输出:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
请注意,此答案取决于您的嵌入式系统是否具有符合这些细节标准的 printf()
实现 - 许多嵌入式环境没有实现。
https://stackoverflow.com/questions/5007487/