开发者

Format float\double numbers to CString with zero filling and preset number of digits

I am looking for a simple method to format the following float\double numbers to a CString.

I was hoping to use CString.Format(), but alternatives are welcome as well, as long as it ends up being a CString.

开发者_如何学C
3.45
112.2

To the following format:

00003450
00112200

Notice there should be no decimal point.

Can this be done simply, if so how?


#include <iomanip>
#include <iostream>

std::cout << std::setw(8) << std::setfill('0') << int(int(YourNumber)*1000+.5);

should do the trick.

Edit: Added rounding. Edit: Second int() cast for silencing obscure warnings :-)


f does work.

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));

Alternatively:

//...
#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());
//...

Refs:

  1. CString::Format
  2. printf


Here's a solution using Boost.Format:

#include <boost/format.hpp>

CString f(double d)
{
   return str(boost::format("%1$=08.0f") % (1000*d)).c_str();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜