设置精度和剪辑尾零,但不打印指数
Set Precision and Clip Trailing Zeros but Never Print Exponent
我需要:
- 设置精度,使浮点数四舍五入到百分位(0.111打印为0.11)
- 剪辑尾随零(1.0打印为1)
- 永远不要打印指数(10001打印成10001)
printf( "%.2fn", input ); // handles 1 and 3 but not 2
printf( "%.2gn", 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):
表示浮点数的双参数以[−]ddd格式转换为十进制记数法。Ddd,其中小数点字符后的位数等于精度规格。如果缺少精度,则取6;如果精度为零且未指定#标志,则不显示小数点字符。如果出现小数点字符,则在其前面至少出现一位数字。该值被四舍五入到合适的位数。
下面是一个C代码片段,它在malloc
和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] = ' ';
}
我不知道任何格式说明符将做你正在寻找的。
在将值传递给单独的格式说明符之前预摘要值可能会起作用。例如:
- 将原始浮点数乘以100并四舍五入到最接近的整数
- 赋值给nScaled (int).
- 将mod(nScaled,100)赋值给另一个整数nFractional。
- 将nScaled/100赋值给另一个整数nWhole.
if( nFractional > 0 )
printf("%d.%d", nWhole, nFractional );
else
printf("%d", nWhole );
你可能已经知道了
我认为另一个选择是使用asprintf()函数:它自己动态分配一个适当长度的字符串。一旦字符串被存储,后面的零/点可以被截断:
...
float num;
...
char *digits;
int i=asprintf(&digits, "%.2f", num)-1;
for(; digits[i] !='.'; i--)
if (digits[i] == '0') digits[i] = NULL; else break;
if (digits[i] == '.') digits[i] = NULL;
printf("%sn", digits);
free(digits);
...
遗憾的是,没有办法强制流使用printf
的%f
行为。所以处理这个问题的唯一方法是在必要时手动调整小数点。我添加了一个c++代码示例来处理这个问题:
string fullfloat(static_cast<size_t>(log10(numeric_limits<declval(input)>::max())) + 5U, ' '); // Adding 1 for the 10s place, 1 for the '.' 2 for the decimal places, and 1 for the null
const size_t length = size(fullfloat) - sprintf(data(fullfloat), "%.2f", input );
*(--mismatch(rbegin(fullfloat) + length, next(rbegin(fullfloat), 3U + length), "00.").first) = ' ';
fullfloat
现在将包含正确的字符串,但由于它的大小将超过应用的' '
字符,因此使其打印属性的唯一方法是使用data()
:
cout << data(fullfloat);
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 使用简单类型列表实现的指数编译时间.为什么
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 用C++打印指数形式的素数分解
- 便携式打印双倍到C++个 iostreams 的指数
- 设置精度和剪辑尾零,但不打印指数
- 打印不带指数的 gmplib mpf_t数