2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ABCplus
  • 3,981
  • 3
  • 27
  • 43

1 Answers1

1

Try using this member function of XmlRpcValue:

setDoubleFormat (const char *f)
//Specify the format used to write double values. 
Rama
  • 3,222
  • 2
  • 11
  • 26
  • Ah, interesting, I've never seen that. I suppose I should invoke it like this: setDoubleFormat("%.4f"), correct? – ABCplus Apr 12 '16 at 15:30
  • Yes, the format is the same as sprintf: http://www.cplusplus.com/reference/cstdio/snprintf/ Check out the use in the documentation: http://www.oversim.org/chrome/site/doc/doxy/classXmlRpc_1_1XmlRpcValue.html#ade0d89d285db29286e1f4c336ded5cb4 – Rama Apr 12 '16 at 15:45
  • Since now I'll implement that change, do you think that calling `roundD` in `setXValue` function is still valid or completely unuseful? – ABCplus Apr 13 '16 at 09:42
  • I think it is not useful here, but I don't know if it is used in other part of your code. – Rama Apr 13 '16 at 13:10
  • No, just there. Its original scope was to store a 4 digit double – ABCplus Apr 13 '16 at 15:09