我需要:
- 设置精度,使 float 四舍五入到百分之一的位置( 0.111 打印为 0.11 )
- 剪辑尾随零( 1.0 打印为 1 )
- 永远不要打印指数(1000.1 打印为 1000.1)
printf( "%.2f\n", input ); // handles 1 and 3 but not 2
printf( "%.2g\n", input ); // handles 1 and 2 but not 3
cout << setprecision( 2 ) << input << endl; // handles 1 and 2 but not 3
有没有printf
或 cout
让我处理所有这些的选项?
最佳答案
C11 标准说 %f
和 %F
(7.21.6.1:8):
A double argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the # flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
这是一个 C 代码片段,它在 malloc
ed bloc t
中生成您想要的内容,之后您需要释放这些内容。如果你是用C99写的,也可以考虑变长数组。
下面的代码没有为转换引入任何额外的近似值(如果您的 printf
打印出正确舍入为十进制的转换,下面的代码也将如此),并且适用于所有浮点值。
#include <stdio.h>
#include <stdlib.h>
…
int len = snprintf(0, 0, "%.2f", input);
if (len < 0) fail();
char *t = malloc((size_t)len + 1);
if (!t) fail();
if (sprintf(t, "%.2f", input) < 0) fail();
len--;
if (t[len] == '0') {
len--;
if (t[len] == '0') {
len--;
if (t[len] == '.') len--;
}
t[len + 1] = '\0';
}
关于c++ - 设置精度和裁剪尾随零但从不打印指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25403713/