C++ 使用 printf 打印浮点数时额外的前导零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2486410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extra leading zeros when printing float using printf?
提问by shoosh
I'd like to be able to write a time string that looks like this: 1:04:02.1 hours
using printf.
When I try to write something like this:
我希望能够编写一个如下所示的时间字符串:1:04:02.1 hours
使用 printf。
当我尝试写这样的东西时:
printf("%d:%02d:%02.1f hours\n", 1, 4, 2.123456);
I get:
我得到:
1:04:2.1 hours
Is it possible to add leading zeros to a float formatting?
是否可以将前导零添加到浮点格式?
回答by AndiDog
With the %f
format specifier, the "2" is treated as the minimum number of characters altogether, not the number of digits before the decimal dot. Thus you have to replace it with 4 to get two leading digits + the decimal point + one decimal digit.
对于%f
格式说明符,“2”被视为最小字符总数,而不是小数点前的位数。因此,您必须将其替换为 4 才能获得两位前导数字 + 小数点 + 一位小数。
printf("%d:%02d:%04.1f hours\n", 1, 4, 2.123456);
回答by kennytm
Try %04.1f
instead of %02.1f
. The "4" here means at least 4 characters will be printed, and "2.1" has 3 (> 2) characters, so to enable the padding zeros you need 4.
尝试%04.1f
代替%02.1f
. 这里的“4”表示至少会打印 4 个字符,而“2.1”有 3 (> 2) 个字符,因此要启用填充零,您需要 4 个。