Search code examples
c++formattingfloating-pointcstring

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.

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?


Solution

  • 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