如何在printf中隐藏前导零

Chr*_*ann 23 c double printf

以下输出0.23.如何让它简单输出.23

printf( "%8.2f" , .23 );
Run Code Online (Sandbox Code Playgroud)

Mic*_*urr 26

C标准说,对于fF浮点格式说明:

如果出现小数点字符,则在其前面至少出现一个数字.

我认为如果你不想在小数点之前出现零,你可能需要做一些事情,比如snprintf()用来将数字格式化为字符串,0如果格式化的字符串以"0"开头,则删除它.(类似于"-0.").然后将格式化的字符串传递给我们的实际输出 或类似的东西.


Jer*_*NER 5

只能使用它是不可能的printf.文件printf说:

f  - "double" argument is output in conventional form, i.e.
     [-]mmmm.nnnnnn
     The default number of digits after the decimal point is six,
     but this can be changed with a precision field. If a decimal point
     appears, at least one digit appears before it. The "double" value is
     rounded to the correct number of decimal places.
Run Code Online (Sandbox Code Playgroud)

请注意,如果出现小数点,则至少会出现一个数字.

因此,您似乎必须手动编码自己的格式化程序.


Iva*_*ack 5

只需将其转换为具有所需精度的整数即可

double value = .12345678901; // input
int accuracy = 1000; // 3 digit after dot
printf(".%03d\n", (int)(value * accuracy) );
Run Code Online (Sandbox Code Playgroud)

输出:

.123
Run Code Online (Sandbox Code Playgroud)

Pastebin 上的示例源