作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 double
,格式为 xxxxx.yyyy
,例如 0.001500
。
我想把它转换成wstring
,用科学记数法格式化。这是我想要的结果:0.15e-2
。
我对 C++ 没有那么多经验,所以我查看了 std::wstring
reference并且还没有找到任何可以执行此操作的成员函数。
我找到了 similar threads在 Stack Overflow 上,但我不知道如何应用这些答案来解决我的问题,尤其是因为它们不使用 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
和 scientific 表示法。
我只想将 double
转换为 wstring
,并使用科学记数法对生成的 wstring
进行格式化。
最佳答案
您可以使用 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
。
关于c++ - 将double转换为wstring,但wstring必须用科学计数法格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948155/
我是一名优秀的程序员,十分优秀!