将double转换为wstring,但wstring必须用科学计数法格式化

Convert double to wstring, but wstring must be formatted with scientific notation

我有一个格式为 xxxxx.yyyydouble,例如 0.001500

我想把它转换成wstring,用科学计数法格式化。这是我想要的结果:0.15e-2.

我对 C++ 没有那么多经验,所以我检查了 std::wstring reference 并没有找到任何可以执行此操作的成员函数。

我在 Stack Overflow 上找到了 similar threads,但我只是不知道如何应用这些答案来解决我的问题,尤其是因为他们不使用 wchar

我已经尝试自己解决这个问题:

// get the value from database as double
double d = // this would give 0.5

// I do not know how determine proper size to hold the converted number 
// so I hardcoded 4 here, so I can provide an example that demonstrates the issue
int len = 3 + 1;  // + 1 for terminating null character
wchar_t *txt = new wchar_t[3 + 1];
memset(txt, L'[=10=]', sizeof(txt));
swprintf_s(txt, 4, L"%e", d);
delete[] txt;

我只是不知道如何分配足够大的缓冲区来保存转换结果。每次我得到缓冲区溢出,这里的所有答案都来自类似的线程 estimate 大小。我真的很想避免这种引入 "magic" 数字的方式。

我也不知道如何使用stringstream,因为那些答案没有用科学 符号将double 转换成wstring

我想要的只是将 double 转换为 wstring,结果 wstring 被格式化为科学记数法。

您可以使用 std::wstringstreamstd::scientific 标志来获得您正在寻找的输出 wstring

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

int main(int argc, char * argv[])
{
    double val = 0.001500;
    std::wstringstream str;
    str << std::scientific << val;
    std::wcout << str.str() << std::endl;
    return 0;
}

您还可以使用附加输出标志设置浮点精度。查看 reference page 了解更多您可以使用的输出操纵器。不幸的是,我不相信您的样本预期输出是可能的,因为正确的科学记数法是 1.5e-3.