Search code examples
c++floating-pointdecimalxml-rpc

Round a double and send it over XML-RPC


I need to round some double values to four decimals maximum, and then send them over XML-RPC using this library.

What I've done so far is the following:

First of all I have a round function:

double roundD(double x, unsigned int precision = 4)
{
    return round(x * pow(10.0, double(precision))) / pow(10.0, double(precision));
}

and it works fine, according to this.

In my application, I've a set method setXValue that takes a double and a toXmlRpc() method to output an XmlRpcValue object:

class Point{
public:
    Point(double x, double y) {m_x = x; m_y=y;}

    void Point::setXValue(double x)
    {
        m_x = roundD(x);
    }

    XmlRpcValue Point::toXmlRpc() const
    {
         XmlRpcValue xmlrpcvalue;
         xmlrpcvalue["x"] = m_x;
         return xmlrpcvalue;
    }

private:
    double m_x;
    double m_y;

What I store in the XML-RPC value is not a rounded double. In fact, when receiving that XML-RPC answer, I see good values like 0.3488, 0.1154 for example, but also values in the form of 9.059900000000001 or 8.990399999999999.

I'm sure my roundD function works fine (I've tested it in the C++ playground) so where the issue is located?

I cannot store the value in the XmlRpcValue object like this:

char str[80];
sprintf(str, "%.4f", m_x);
xmlrpcvalue["x"] = str;

Otherwise I would change the xml-rpc data type, and that is not correct.


Solution

  • Try using this member function of XmlRpcValue:

    setDoubleFormat (const char *f)
    //Specify the format used to write double values.