C语言 printf 可变小数位数的浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16413609/
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
Printf variable number of decimals in float
提问by Wine Too
I found interesting format for printing nonterminated fixed length strings like this:
我发现了打印非终止固定长度字符串的有趣格式,如下所示:
char newstr[40] = {0};
sprintf(newstr,"%.*s", sizeof(mystr), mystr);
So I think maybe is there a way under printf command for printing a float number...
所以我想也许在 printf 命令下有一种方法可以打印浮点数......
"%8.2f"
“%8.2f”
to have ability to choose number of decimals with integer number.
能够选择整数的小数位数。
Something like this:
像这样的东西:
sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)
EDIT - Solution:
(for rounding and clearing a float number to desired precision).
编辑 - 解决方案:(
用于将浮点数四舍五入和清除到所需精度)。
int precision = 2;
char kolf[16] = {0};
sprintf(kolf, "%8.*f", precision, mystruct.myfloat);
float kol = atof(kolf);
回答by Andreas Fester
You can also use ".*"with floating points, see also http://www.cplusplus.com/reference/cstdio/printf/(refers to C++, but the format specifiers are similar)
您也可以".*"与浮点一起使用,另请参见http://www.cplusplus.com/reference/cstdio/printf/(指的是 C++,但格式说明符类似)
.number: For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
...
.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.number:对于 a、A、e、E、f 和 F 说明符:这是小数点后要打印的位数(默认情况下,这是 6)。
...
.*:精度未在格式字符串中指定,而是作为必须格式化的参数之前的附加整数值参数。
For example:
例如:
float floatnumbervalue = 42.3456;
int numberofdecimals = 2;
printf("%.*f", numberofdecimals, floatnumbervalue);
Output:
输出:
42.35
回答by Some programmer dude
You can use the asterisk for that too, both for the field width and the precision:
您也可以将星号用于字段宽度和精度:
printf("%*.*f\n", myFieldWidth, myPrecision, myFloatValue);
See e.g. this reference.
参见例如这个参考。

