On 08/21/2014 11:53 AM, nrgyzer wrote:

>      double d = 1.23456789;
>      JSONValue j = d;
>      sendToRemote(toJSON(&j));
> }
>
> My problem is that the remote PC receives 1.23457 instead of
> 1.23456789.

I think it is due to the following code simply calling to!string in std/phobos/json.d:

            case JSON_TYPE.FLOAT:
                json.put(to!string(value.store.floating));
                break;

> But when I add the following:
>
> import std.json;
> import std.stdio;
> void main()
> {
>      double d = 1.23456789;
>      JSONValue j = d;
>      sendToRemote(toJSON(&j));
>      writefln("%.8f", j.floating);
> }
>
> writefln() shows me 1.23456789. So, the value is correct.

It is more precise but still not correct because that specific double value cannot be represented exactly.

> Is there any chance I can send 1.23456789
> instead of 1.23457 to my remote PC?

You can call a function like the following:

import std.string;
import std.json;
import std.stdio;

string morePrecisely(double d)
{
    return format("%.20g", d);
}

void main()
{
    double d = 1.23456789;
    JSONValue root = [ "value" : d.morePrecisely ];
    writeln(toJSON(&root));
}

Of course do something more sensible than hard-coding the 20 in that format string. :)

> Note: I cannot use strings because the other PC expects a numeric
> data type.

I don't think it is a concern as JSON does not encode types. It is up to the receiver how to interpret the data. Here is the output of the program above:

{"value":"1.2345678899999998901"}

Ali

Reply via email to