c++ - 设置精度和裁剪尾随零但从不打印指数

标签 c++ c floating-point printf cout

我需要:

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

有没有printfcout让我处理所有这些的选项?

最佳答案

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 代码片段,它在 malloced 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/

相关文章:

c - 如何在 OS X 中禁用 .text 重定位?

math - float 学有问题吗?

rust - 如何在不进行手动解析的情况下从可能包含剩余字符的字符串中解析 float ?

c++ - C++可变参数模板参数方法传递给没有可变参数的方法

c++ - 我可以打开多个 QWebView 实例来模拟打开 N 个浏览器吗?

c - CodeBlocks 中的奇怪警告 - C

python - 在 Python 中比较两个 float 是否相等

c++ - 如何使用尽可能短的代码反向移植 if constexpr?

c++ - 是否有一种不令人讨厌的方法来 Doxygen 类头文件?

将 `%*s` 与 `printf` 一起使用时出现编译器警告