我的double
格式为xxxxx.yyyy
,例如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'\0', sizeof(txt));
swprintf_s(txt, 4, L"%e", d);
delete[] txt;
我只是不知道如何分配足够大的缓冲区来保存转换结果。每次我得到缓冲区溢出,这里的所有答案都来自类似的线程估计的大小。我真的想避免这种类型的引入“魔术”数字。
我也不知道如何使用stringstream
,因为这些答案未使用科学符号将double
转换为wstring
。
我想要的只是将double
转换为wstring
,并使用科学记数法格式化wstring
。
答案 0 :(得分:2)
您可以使用std::wstringstream
和std::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
。