[Solved] Format double value in c++ [closed]


In C++ you can use std::stringstream and precision property:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    double d = 50.0123456789;
    std::string s;
    std::stringstream sstream;
    sstream.setf(std::ios::fixed);
    sstream.precision(1);
    sstream << d;

    s = sstream.str();
    std::cout << d << std::endl;
    std::cout << s << std::endl;
    return 0;
}

Note, that precision inherited from std::ios_base, so std::cout has it too. If you simply want output this value, you can set std::cout.precision() to 1.

Also you can find more about this on
http://www.cplusplus.com/reference/ios/ios_base/precision/ and
http://www.cplusplus.com/reference/sstream/stringstream/

solved Format double value in c++ [closed]