我正在寻找一种将以下 float\double 数字格式化为 CString的简单方法。
我希望使用 CString.Format(),但也欢迎使用替代方法,只要它最终成为 CString。
3.45
112.2
转为以下格式:
00003450
00112200
注意不应该有小数点。
这可以简单地完成吗,如果可以的话怎么做?
我正在寻找一种将以下 float\double 数字格式化为 CString的简单方法。
我希望使用 CString.Format(),但也欢迎使用替代方法,只要它最终成为 CString。
3.45
112.2
转为以下格式:
00003450
00112200
注意不应该有小数点。
这可以简单地完成吗,如果可以的话怎么做?
#include <iomanip>
#include <iostream>
std::cout << std::setw(8) << std::setfill('0') << int(int(YourNumber)*1000+.5);
应该做的伎俩。
编辑:添加了四舍五入。编辑:第二个 int() 演员用于消除晦涩的警告:-)
f
确实有效。
void f(double a) {
const int a1000 = static_cast<int>(a * 1000 + 0.5);
assert(a1000 < 100000000);
const int b = a1000 + 100000000;
std::stringstream ss;
ss << b;
std::cout << ss.str().c_str() + 1; //remove first 1;
}
int main() {
f(3.45);
f(112.2);
}
CString myString;
myString.Format(_T("%08d"), static_cast<int>(num * 1000.0 + 0.5));
或者:
//...
#include <sstream>
#include <iomanip>
using namespace std;
//...
ostringstream s;
s << setfill('0') << setw(8) << static_cast<int>(num * 1000.0 + 0.5);
CString myString(s.str().c_str());
//...
参考:
这是使用Boost.Format的解决方案:
#include <boost/format.hpp>
CString f(double d)
{
return str(boost::format("%1$=08.0f") % (1000*d)).c_str();
}