Search code examples
c++xmlc++11pugixml

Pugi XML: How to set the precision for float numbers


I use pugi::XML parser and i want to set the precision for the floating point numbers. I have already used the rounding function on the float variable, but while printing with pugi::xml, it is printed with 6 decimal digits.

I use below statement to print value in C++11 :

subNode.append_child(pugi::node_pcdata).set_value(to_string(doubleVal).c_str());

Example:

<value>97.802000</value>

must be printed as

<value>97.802</value>

How can i do that ?


Solution

  • Try this:

    #include <iomanip> // setprecision
    #include <sstream> // stringstream
    
    std::string toStringPrecision(double input,int n)
    {
        stringstream stream;
        stream << std::fixed << setprecision(n) << input;
        return stream.str();
    }
    

    Then you call it in:

    subNode.append_child(pugi::node_pcdata).set_value(toStringPrecision(doubleVal,3).c_str());