c - 'printf' 在 C 中带有前导零

我有一个 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/

相关文章:

c# - 将小数格式化为两位或整数

.net - 格式化 LINQ 查询的最佳方法

javascript - 用于在 JavaScript 中格式化数字的正则表达式

java - Eclipse 在哪里存储首选项?

sql-server - 如何在sql中获得小数点后2位?

javascript - 如何在javascript中将完整日期转换为短日期?

reporting-services - Reporting Services [SSRS] 表达式

php - 在 PHP 中打印货币数字格式

c# - 在 C# 中,将字符串格式化为 XML 的最佳方法是什么?

bash - 如何在 bash 中打印一些文本并用空格填充到一定宽度?