设置精度和剪辑尾零,但不打印指数

Set Precision and Clip Trailing Zeros but Never Print Exponent

本文关键字:打印 指数 精度 设置      更新时间:2023-10-16

我需要:

  1. 设置精度,使浮点数四舍五入到百分位(0.111打印为0.11)
  2. 剪辑尾随零(1.0打印为1)
  3. 永远不要打印指数(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

是否有printfcout选项可以让我处理所有这些?

C11标准规定%f%F (7.21.6.1:8):

表示浮点数的双参数以[−]ddd格式转换为十进制记数法。Ddd,其中小数点字符后的位数等于精度规格。如果缺少精度,则取6;如果精度为零且未指定#标志,则不显示小数点字符。如果出现小数点字符,则在其前面至少出现一位数字。该值被四舍五入到合适的位数。

下面是一个C代码片段,它在malloct块中生成您想要的内容,之后您需要释放这些内容。如果用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);