user2013121
user2013121

Reputation: 37

what is the equivalent of ToString("00.00000") in C++?

I tried the following to get .ToString("00.00000") but failed

char buf[500];
memset(buf, 0, sizeof(buf));
sprintf_s(buf, "%02.7f",abc);
std::string abc_str = buf;

i realised that the %02 doesnt have any effects, example when i get a 7.0, the result is 7.0000000 rather than the desired 07.0000000, anything wrong here?

Thanks!

Upvotes: 1

Views: 113

Answers (2)

user4164058
user4164058

Reputation: 555

The equivalent in C++ would be:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setw(10) << std::setfill('0') 
              << std::fixed    << std::setprecision(7) << 7.0;
    return 0;
}

Output:

07.0000000

If you need to actually store it into a std::string, then:

#include <sstream>

std::ostringstream oss;
// ...
std::string s = oss.str();

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81926

Code:

#include <stdio.h>

int main() {
    char buf[500];
    printf("%010.7f\n", 7.0);
}

Output:

07.0000000

Comments

Note that 10 is the minimum width of the entire field, not just the left hand side of the decimal.

Upvotes: 0

Related Questions