c++ - 如何以下列方式格式化 double ?

标签 c++ c++11 string-formatting

我正在使用 C++,我想用以下明显的方式格式化 double 。我曾尝试使用 stringstream 来玩“固定”和“科学”,但我无法获得所需的输出。

double d = -5; // print "-5"
double d = 1000000000; // print "1000000000"
double d = 3.14; // print "3.14"
double d = 0.00000000001; // print "0.00000000001"
// Floating point error is acceptable:
double d = 10000000000000001; // print "10000000000000000"

根据要求,这是我尝试过的事情:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

string obvious_format_attempt1( double d )
{
    stringstream ss;
    ss.precision(15);
    ss << d;
    return ss.str();
}

string obvious_format_attempt2( double d )
{
    stringstream ss;
    ss.precision(15);
    ss << fixed;
    ss << d;
    return ss.str();
}

int main(int argc, char *argv[]) 
{
    cout << "Attempt #1" << endl;
    cout << obvious_format_attempt1(-5) << endl;
    cout << obvious_format_attempt1(1000000000) << endl;
    cout << obvious_format_attempt1(3.14) << endl;
    cout << obvious_format_attempt1(0.00000000001) << endl;
    cout << obvious_format_attempt1(10000000000000001) << endl;

    cout << endl << "Attempt #2" << endl;
    cout << obvious_format_attempt2(-5) << endl;
    cout << obvious_format_attempt2(1000000000) << endl;
    cout << obvious_format_attempt2(3.14) << endl;
    cout << obvious_format_attempt2(0.00000000001) << endl;
    cout << obvious_format_attempt2(10000000000000001) << endl;

    return 0;
}

打印以下内容:

Attempt #1
-5
1000000000
3.14
1e-11
1e+16

Attempt #2
-5.000000000000000
1000000000.000000000000000
3.140000000000000
0.000000000010000
10000000000000000.000000000000000

最佳答案

程序无法知道如何按照您所描述的方式格式化数字,除非您编写一些代码以某种方式分析数字 - 即使那样也很难。

这里需要知道源代码中的输入格式,一旦编译器将十进制输入源代码转换为二进制形式存储在可执行文件中,这一点就丢失了。

一种可行的替代方法是输出到 stringstream,然后修改输出以去除尾随零。像这样:

string obvious_format_attempt2( double d )
{
    stringstream ss;
    ss.precision(15);
    ss << fixed;
    ss << d;
    string res = ss.str();
    // Do we have a dot?
    if ((string::size_type pos = res.rfind('.')) != string::npos)
    {
       while(pos > 0 && (res[pos] == '0' || res[pos] == '.')
       {
           pos--;
       }
       res = res.substr(pos);
    }
    return res;
}

我实际上并没有厌倦它,但作为一个粗略的草图,它应该可以工作。警告是,如果你有类似 0.1 的东西,它可能会打印为 0.09999999999999285 或类似的东西,因为 0.1 不能以二进制的精确形式表示。

关于c++ - 如何以下列方式格式化 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302321/

相关文章:

帮助字符串中出现 '%' 的 Python argparse 错误

c++ - 范围错误消息

c++ - 从 QML(Qt Quick 应用程序)调用 C++ 方法

以 ~ 开头的 C++ 路径

c++ - 静态转换如何在 C++ 中保持数字的精度?

c++ - 用于检测模板函数的 Sfinae 类型特征不适用于 std::forward

php - MySQL 使用 PHP sprintf 插入到 NULL INT 列

c++ - Rapidjson:向文档添加外部子文档

c++ - 如何表达转发引用的常量?

python - 如何将 24 小时时间转换为 12 小时时间?